创建一个js文件
export default {
//限定在当前模块的命名空间中,可以使用点语法点该文件名来操作数据和方法
namespaced: true,
state: {
userInfo: {
token: '123',
user: {
}
}
},
mutations: {
setUserInfo(state, data) {
console.log(data);
state.userInfo = data;
}
},
actions: {
login({ commit }, data) {
commit('setUserInfo', data);
}
},
getters: {
getToken(state) {
return state.userInfo.token;
}
}
};
import { createStore } from 'vuex'
import A from '../store/ModulesA/A'
export default createStore({
state: {
id:1,
list: [1,2,3,4,5,6,7,8,9]
},
getters: {
getName(state){
return state.list.filter(item => item > 6)
}
},
mutations: {
Add(state){
state.id=2
}
},
actions: {
},
modeles 进行引入
modules: {
A
}
})
<script>
import { mapState, mapGetters, mapMutations } from "vuex";
export default {
data() {
return {
num: 0,
};
},
computed: {
// state 中的数据放在computed里面使用
...mapState('A',["userInfo"]),
},
mounted() {
this.Getstate();
this.GetA()
},
methods: {
...mapMutations('A',['setUserInfo']),
Getstate() {
// 使用方法
this.num = this.$store.getters.getName;
console.log(this.num);
// this.Add()
// dispath 异步操作 调取action中的方法 commit 调用matations中的操作
this.$store.commit("Add");
},
// 分模块存储的使用方法
GetA(){
this.setUserInfo('123123')
console.log(this.$store.state.A.userInfo)
}
},
};
</script>