模块化的方法
- 在./src目录下新建store目录新建index.js 【./src/store/index.js】,在./src/main.js中import,
import store from './store'
import Vue from "vue";
import Vuex from "vuex";
import yqfk from "./yqfk";
Vue.use(Vuex);
const state = {};
const mutations = {};
const actions = {};
export default new Vuex.Store({
state,
mutations,
actions,
modules: {
yqfk
}
});
- 在上述store目录下,新建yqfk.js【./src/store/yqfk.js】,导出,在index.js中导入到modules字段中
const state = {
test:1
};
const getters = {
testGetter(state){
return state.test
}
}
const mutations ={
}
const actions = {
}
export default {
namespaced:true,
state,
getters,
mutations,
actions,
}
- 在vue单页中使用
- state:【this.$store.state.模块名.key】
- getters:【this.$store.getters[‘模块名/key’]】
- mutations:【this.$store.commit(‘模块名/method’)】
- actions:【this.$store.dispatch(‘模块名/method’)】
<script>
export default {
name: "Home",
computed:{
test(){
return this.$store.state.yqfk.test
},
getTest(){
return this.$store.geters['yqfk/testGetter']
}
}
};
</script>
4.mapState
,mapGetters
,mapMutations
,mapActions
使用
<script>
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'
export default {
name: "Home",
computed:{
// 两种取模块中的state值的方法
...mapState({
test:state => state.yqfk.test
}),
...mapState('yqfk',{
test:state => state.test
}),
...mapGetters('yqfk',{
getTest: 'testGetter'
})
}
};
</script>