vue实现全局变量
Vue 中实现全局变量的方法
在 Vue 中,可以通过多种方式实现全局变量的管理,以下是几种常见的方法:
使用 Vue.prototype
通过扩展 Vue 的原型链,可以将变量或方法挂载到 Vue 实例上,从而在所有组件中通过 this 访问。

// main.js
Vue.prototype.$globalVar = 'This is a global variable';
// 组件中使用
export default {
mounted() {
console.log(this.$globalVar); // 输出: This is a global variable
}
}
使用 Vuex 状态管理
Vuex 是 Vue 的官方状态管理库,适合管理复杂的全局状态。
// store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
globalVar: 'This is a global variable'
},
mutations: {
setGlobalVar(state, value) {
state.globalVar = value;
}
}
});
// main.js
import store from './store';
new Vue({
store,
// ...其他配置
});
// 组件中使用
export default {
computed: {
globalVar() {
return this.$store.state.globalVar;
}
},
methods: {
updateGlobalVar() {
this.$store.commit('setGlobalVar', 'New value');
}
}
}
使用全局事件总线
通过创建一个全局的 Vue 实例作为事件总线,实现跨组件通信。

// eventBus.js
import Vue from 'vue';
export const EventBus = new Vue();
// 组件A中发送事件
EventBus.$emit('updateGlobalVar', 'New value');
// 组件B中监听事件
EventBus.$on('updateGlobalVar', (value) => {
console.log(value); // 输出: New value
});
使用 provide/inject
Vue 的 provide 和 inject 允许祖先组件向所有子孙组件注入依赖。
// 祖先组件
export default {
provide() {
return {
globalVar: 'This is a global variable'
};
}
};
// 子孙组件
export default {
inject: ['globalVar'],
mounted() {
console.log(this.globalVar); // 输出: This is a global variable
}
};
使用 window 对象
直接将变量挂载到 window 对象上,但这种方式不推荐,因为容易造成全局污染。
// main.js
window.globalVar = 'This is a global variable';
// 组件中使用
export default {
mounted() {
console.log(window.globalVar); // 输出: This is a global variable
}
};
选择建议
- 简单场景:使用
Vue.prototype或provide/inject。 - 复杂状态管理:使用 Vuex。
- 跨组件通信:使用事件总线。
- 避免直接使用
window对象。






