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);
}
 
// 这样调出的结果确实是一样的。到此全局变量完毕


  • 2021-01-05 15:41:42

    nodejs修改时区

    ​let date = new Date(); date.setHours(date.getHours() + 8);

  • 2021-01-06 23:09:38

    mp3解码器转PCM合并

    首先,为了混合两个音频文件,您需要操纵它们的原始表示;由于MP3文件被压缩,您无法直接访问信号的原始表示.您需要对压缩的MP3流进行解码,以便“理解”您的音频信号的波形,然后可以混合使用.

  • 2021-01-08 16:47:37

    nodejs如何使用fetch

    node 中没有实现 fetch,你可以使用 node-fetch,使得在 node 中也可以使用 fetch.

  • 2021-01-08 16:49:59

    CommonJs 与 ESModule区别

    node中模块导入require是一个内置的函数,因此只有在运行后我们才可以得知模块导出内容,无法做静态分析