vue定于全局变量的几种方式

430 阅读1分钟

1.定义专用模块来配置全局变量

通过定义专用模块来配置全局变量,然后在通过export的方式将模块暴露出来,在需要引用的组件中引入即可。

global.vue

const a = 1 
export default {
    a
}

然后引入 global.vue

import global from 'global.vue'

2.通过全局变量挂载到Vue.prototype

main.js

Vue.prototype.a = 1

组件调用

console.log(this.a);

3.使用window 对象

window.a = 1

4.使用vuex

安装:

npm install vuex --save

新建store.js文件

import Vue from 'vue'
import Vuex from 'vuex';
Vue.use(Vuex);

export default new Vuex.Store({
  state:{
    a:1
  }
})

main.js 中引入

import store from './store'
new Vue({
el: '#app',
router,
store, 
components: { App },
template: '<App/>' 
});

组件内调用

console.log(this.$store.state.a)