vue怎样定义全局变量

项目需要定义一个全局变量供所有vue实例使用,首先在common.js中:

import axios from 'axios';

const api = {
  async getLanguagesList() {
    const url = `${baseUrl}/xxxxxx`;
    const res = await axios.get(url);
    return res;
  },
}

export default api;

在main.js中引用:

import api from './common';
Vue.prototype.$api = api;

然后就可以直接在vue实例中使用了:

async created() {
    this.$api.getLanguagesList();
  }

至于为什么$ api要以$开头?
$ 是在 Vue 所有实例中都可用的属性的一个简单约定。这样做会避免和已被定义的数据、方法、计算属性产生冲突。
详见:https://cn.vuejs.org/v2/cookbook/adding-instance-properties.html

发布了10 篇原创文章 · 获赞 0 · 访问量 1581

猜你喜欢

转载自blog.csdn.net/weixin_45266779/article/details/100043062