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-04-15 23:54:49

    ViewPager+Fragment取消预加载以及禁止滑动

    取消预加载 网上了解了很多取消预加载的方法,里面提到了使用一个viewpager的public方法setOffscreenPageLimit 经过查看源码以及验证发现该方法是管理Viewpager预加载的页数,最低也是默认为一页(例如ViewPager一共有4页,当前手机屏幕显示第一页

  • 2017-04-15 23:56:30

    onInterceptTouchEvent和onTouchEvent调用关系详解

    如果没有onInterceptTouchEvent,只考虑onTouchEvent的话,比较容易分析和理解。假如有三层布局结构,linearLayout1,linearLayout2,textView,从前到后是包含的关系。那么下面分情况说明。

  • 2017-04-16 19:36:32

    ViewPager预加载问题和onCreateView多次调用问题的解决

    1,在使用ViewPager嵌套Fragment的时候,由于VIewPager的几个Adapter的设置来说,都会有一定的预加载(默认是左右各一个Frament)。通过设置setOffscreenPageLimit(int number) 来设置预加载的熟练,在V4包中,默认的预加载是1,即使你设置为0,也是不起作用的,设置的只能是大于1才会有效果的。我们需要通过更改V4包中的默认属性才可以

  • 2017-04-16 21:02:55

    ImageView的android:adjustViewBounds属性

    取值为true时: Adjust the ImageView's bounds to preserve the aspect ration of its drawable. 调整ImageView的界限来保持图像纵横比不变。 这并不意味着ImageView的纵横比就一定和图像的纵横比相同

  • 2017-04-18 17:12:50

    Laravel 读取 config 下的数据

    Laravel的config下一般存放配置信息,可以通过config('key')方法获取指定的数据。 设置值可通过「点」式语法读取,其中包含要访问的文件名以及选项名称。