使用 module,不使用 namespaced
情況:
- 可能存在重復(fù)的action或者mutation
- vue組件使用watch,必須需要用上getter,
否則只靠computed計(jì)算state是無法watch
親測(cè),可行代碼
vuex里面
//基于axios封裝接口,返回是一個(gè)promise
import api from '@/api/mock.js';
export default {
state : {
test_num: 0
},
getters : {
test_num: state => state.test_num,
},
mutations: {
SET_test_num(state, res) {
state.test_num = res;
},
},
actions : {
test_num({dispatch, commit, state}, query) {
/****------ 模擬 并且 判斷 前期錯(cuò)誤 ------****/
// {}
return api.test_num(query)
.then((res) => {
/****------進(jìn)行所有的 后期判斷------****/
let {data, code} = res.data;
if (code >= 400 && code < 500) {
commit('whole_notice', {title: `test_num`, desc: '接口出錯(cuò)'});
throw new Error('test_num 接口出錯(cuò)', err);
return;
}
if (!data.length) {
commit('whole_notice', {title: `test_num`, desc: '接口無數(shù)據(jù)'});
}
/****------目的------****/
commit('SET_test_num', data);
})
.catch((err) => {
throw new Error('test_num 接口出錯(cuò)', err);
});
},
}
};
vue組件里面:
computed:{
...mapGetters(['test_num'])
},
watch:{
test_num(val){
console.log(11111);
}
},
created(){
this.$store.dispatch('test_num')
}
使用 module,使用 namespaced
情況:
- 相對(duì)比較繁瑣,必須加上模塊名稱,才能使用
- 無法在webstorm中,ctrl+鼠標(biāo)點(diǎn)擊進(jìn)行跳轉(zhuǎn)
- 不需要getter也能夠用watch
親測(cè),可行代碼
vuex里面
//基于axios封裝接口,返回是一個(gè)promise
import api from '@/api/mock.js';
export default {
namespaced:true,
state : {
test_num: 0
},
getters : {
},
mutations: {
SET_test_num(state, res) {
state.test_num = res;
},
},
actions : {
test_num({dispatch, commit, state}, query) {
/****------ 模擬 并且 判斷 前期錯(cuò)誤 ------****/
// {}
return api.test_num(query)
.then((res) => {
/****------進(jìn)行所有的 后期判斷------****/
let {data, code} = res.data;
if (code >= 400 && code < 500) {
commit('whole_notice', {title: `test_num`, desc: '接口出錯(cuò)'});
throw new Error('test_num 接口出錯(cuò)', err);
return;
}
if (!data.length) {
commit('whole_notice', {title: `test_num`, desc: '接口無數(shù)據(jù)'});
}
/****------目的------****/
commit('SET_test_num', data);
})
.catch((err) => {
throw new Error('test_num 接口出錯(cuò)', err);
});
},
}
};
vue組件里面:
computed:{
...mapState('login',['test_num'])
},
watch:{
test_num(val){
console.log(11111);
}
},
created(){
this.$store.dispatch('login/test_num')
}