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-11-01 01:30:45

    解决第三方包内jar包冲突

    这个问题就是因为引入jar包的冲突,这时我们可以在build.gradle中添加如下代码,下方单独的是添加的代码

  • 2017-11-06 01:00:17

    撤销git add

    如何撤销git add,不小心执行了git add . 操作,但是又不能提交所有的文件,因为对应不同的分支,现在怎么样可以将git add 撤销回来

  • 2017-11-10 00:06:15

    CORS: credentials mode is 'include'

    XMLHttpRequest cannot load http://localhost/Foo.API/token. The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:5000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.