- 安装
npm install vuex --save
- 新建store.js文件并在main.js中引入
import Vuex from 'vuex';
import store from './assets/store';
Vue.use(Vuex);
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
- store.js文件中
此处注意 export default new Vuex.Store 大小写,否则会出错的
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
sec_name:'',
},
mutations:{
charge_path(state,path){
state.sec_name = path.sec_name
}
}
})
- 在A组件中设置vuex中需要的值
let json = {
sec_name: "我的订单",
};
this.$store.commit("charge_path", json);
- 在B页面的vuex中对应的值会立即做出改变
this.$store.state.sec_name //我的订单
用vuex在兄弟组件之间通讯实在是简单粗暴…挺好