1、安装Vuex:
npm install vuex --save
2、创建store.js:
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
globalVar: '这是一个全局状态'
},
mutations: {
updateGlobalVar(state, payload) {
state.globalVar = payload;
}
}
})
3、在main.js
中引入并配置store:
// main.js
import Vue from 'vue'
import App from './App'
import store from './store'
const app = new Vue({
store,
...App
});
app.$mount();
4、使用全局状态:
// 在页面或组件中
export default {
computed: {
globalVar() {
return this.$store.state.globalVar;
}
},
methods: {
updateGlobalVar(newValue) {
this.$store.commit('updateGlobalVar', newValue);
}
}
}