非模块化下的vuex各方法的调用与获取
目录结构
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6b2cbfde1cdbba79204e94bfce2bf7e2.png)
index.js代码
import Vuex from "vuex";
import Vue from "vue";
import setting from './modules/setting'
const state = {
sum: 12,
userInfo: {
username: '张三',
token: 'hnI6UOiu2GJKN42jhnknJiB7s'
}
}
const mutations = {
jia(state,num){
state.sum += num;
},
jian(state,num){
state.sum -= num;
}
}
const getters = {
bigSum(state){
return state.sum * 10;
}
}
const actions = {
asyncJian(context,value){
context.commit('jian',value)
}
}
const modules = {
setting,
}
Vue.use(Vuex);
export default new Vuex.Store({
state,
actions,
mutations,
getters,
modules
});
setting模块代码
const state = {
threm: 'light',
currentTime: '暂未设置时间'
}
const mutations = {
SET_THREM(state,value){
console.log('state :>> ', state);
state.threm = value;
},
SET_TIME(state,value){
state.currentTime = value;
}
}
const actions = {
setTime(store,value){
store.commit('SET_TIME',value);
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
非模块化下使用
import { mapState,mapMutations,mapActions } from 'vuex'
computed: {
...mapState(['userInfo','sum']),
...mapState(
{
userInfo: 'userInfo',
sum: 'sum',
},
),
},
methods: {
...mapMutations(['jia']),
...mapActions(['asyncJian']),
changeSum1(){
this.$store.commit('jia',2);
this.jia(2);
},
asyncChangeSum(){
setInterval(() => {
this.$store.dispatch('asyncJian',2);
this.asyncJian(2);
}, 1000);
}
}
模块化中使用
import { mapState,mapMutations,mapActions } from 'vuex'
computed: {
...mapState('setting',['threm']),
...mapState(
{
threm: state => state.setting.threm,
currentTime: state => state.setting.currentTime,
},
),
},
methods: {
...mapMutations('setting',['SET_THREM']),
...mapActions('setting',['setTime']),
changeThrem(){
this.$store.commit('setting/SET_THREM','drak111');
this.SET_THREM('drak');
},
asyncChangeTime(){
this.$store.dispatch('setting/setTime','2023-06-02');
this.setTime('2023-06-01');
}
}