安装 Vuex: 在每个子应用中都需要安装 Vuex。使用命令 npm install vuex 或 yarn add vuex 在项目中添加 Vuex。
创建 Vuex Store: 在每个子应用中都需要创建自己的 Vuex Store。在子应用的入口文件中,比如 main.js,创建并配置 Vuex Store。
// main.js
import Vue from 'vue';
import Vuex from 'vuex';
import App from './App.vue';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
// Your shared state goes here
},
mutations: {
// Your mutations to update the state go here
},
actions: {
// Your actions to perform asynchronous operations go here
},
getters: {
// Your getters to access state go here
}
});
new Vue({
store,
render: h => h(App)
}).$mount('#app');
定义共享状态: 在 Vuex Store 的 state 中定义需要共享的状态数据。
定义 Mutations: 在 mutations 中定义修改状态的方法,子应用通过调用这些 mutations 来更新共享状态。