一、安装
// 此方式为引入vuex4版本
npm install vuex@next --save
二、引入
vuex3+版本与4+版本有所区别
//vuex3.0
在store文件中 src/store/index.js
import { createStore } from 'vuex'
const store = createStore({
modules: {
user, //表示user模块
},
getters
});
export default store;
//在main.js文件中的导入
import store from './store';
new Vue({
store, //绑定到vue
render: h => h(App)
}).$mount('#app');
//user.js中
const user = {
state: {
},
actions: {
SendLogs({ state, commit },payload) {
//第一个参数是store,可以解构出state, commit...
//第二个参数是接收的值
}
},
mutations: {
SET_SHADE: (state, payload) => {
//第一个参数是state
//第二个参数是接收的值
},
}
};
export default user;
三、在模块中使用
import { mapState,mapGetters,mapActions,mapMutations } from 'vuex'
computed: {
...mapGetters(['tagWel', 'tagList', 'tag', 'website']),
...mapState({
showTag: state => state.common.showTag
}),
},
methods:{
...mapActions(['GetFieldPermission']),
...mapMutations(['SET_TOP_MENU_ID']),
}
四、补充
// 触发actions中的方法使用dispatch
this.$store.dispatch('XXX')
// 触发mutations中的方法使用commit
this.$store.commit('XXX')