nuxtjs 全局变量添加 asyncData 也可访问

2019-11-26 15:26:10

首先在根据根据官方文档,需要做类似插件的引入方式:

1.  /plugins目录下建立main.js 内容为:

import Vue from 'vue' // vue 文件引入 - 方便在vue方法内容直接 this 调取
import Api from './api' // 自定变量内容 其他自便
 
let main = {
    install(Vue) {
        Vue.prototype.$api = Api; // 变量的内容 后期可以在vue中 this->$api.xxx 使用
    }
};
 
Vue.use(main); // 这里不能丢
 
// 这里是 为了在 asyncData 方法中使用
export default ({ app }, inject) => {
    // Set the function directly on the context.app object
    app.$api = Api // 名称
};

/plugins/api.js 文件内容:

let host = 'http://api.xxx.xxx';
 
module.exports = {
    getSolidList: host + '/getSolidList.api'
};

关于写这个main是我的写法,为了方便调入其他的自定义变量文件方便后期扩展啥的,可以根据自己的需要改写。

2 . 根目录下 /nuxt.config.js 的 module.exports下添加内容:

module.exports = {
   // ... 其他配置
    plugins: [
        {src: '@/plugins/main', ssr: true}
    ],
  // ... 其他配置
}

3. 关于使用:

async asyncData (params) {
     return { title: params.app.$api.getSolidList }
},
created() {
    console.log(this.title, this.$api.getSolidList);
}
 
// 这样调出的结果确实是一样的。到此全局变量完毕


  • 2017-02-24 16:53:58

    PHP 中的Closure

    Closure,匿名函数,又称为Anonymous functions,是php5.3的时候引入的。匿名函数就是没有定义名字的函数。这点牢牢记住就能理解匿名函数的定义了。

  • 2017-03-02 09:45:27

    动态加载js和css

    开发过程中经常需要动态加载js和css,今天特意总结了一下常用的方法。