深入理解vuex2.0 之 modules

2020-06-16 06:14:39易采站长站整理

那么怎样才能获取到根store 中的state 和 getters 呢? Vuex 提供了 rootState, rootGetters 作为module 中  getters 中默认参数, actions中context 对象,也会多了两个属性,context.getters, context. rootState,  这些全局的默认参数,都排在局部参数的后面。

我们在store.js中添加 state, getters: 


export default new Vuex.Store({
// 通过modules属性引入login 模块。
modules: {
login: login
},

// 新增state, getters
state: {
job: "web"
},
getters: {
jobTitle (state){
return state.job + "developer"
}
}
})

login 目录下的 index.js


const actions = {
// actions 中的context参数对象多了 rootState 参数
changeName ({commit, rootState},anotherName) {
if(rootState.job =="web") {
commit("CHANGE_NAME", anotherName)
}
}
};

const getters = {
// getters 获取到 rootState, rootGetters 作为参数。
// rootState和 rootGetter参数顺序不要写反,一定是state在前,getter在后面,这是vuex的默认参数传递顺序, 可以打印出来看一下。
localJobTitle (state,getters,rootState,rootGetters) {
console.log(rootState);
console.log(rootGetters);
return rootGetters.jobTitle + " aka " + rootState.job
}
};

app.vue 增加h2 展示 loacaJobTitle, 这个同时证明了getters 也是被注册到全局中的。


<template>
<div id="app">
<img src="./assets/logo.png">
<h1>{{useName}}</h1>

<!-- 增加h2 展示 localJobTitle -->
<h2>{{localJobTitle}}</h2>
<!-- 添加按钮 -->
<div>
<button @click="changeName"> change to json</button>
</div>
</div>
</template>

<script>
import {mapActions, mapState,mapGetters} from "vuex";
export default {
// computed属性,从store 中获取状态state,不要忘记login命名空间。
computed: {
...mapState({
useName: state => state.login.useName
}),

// mapGeter 直接获得全局注册的getters
...mapGetters(["localJobTitle"])
},
methods: {
changeName() {
this.$store.dispatch("changeName", "Jason")
}
}
}
</script>

6, 其实actions, mutations, getters, 也可以限定在当前模块的命名空间中。只要给我们的模块加一个namespaced 属性:


const state = {
useName: "sam"
};
const mutations = {
CHANGE_NAME (state, anotherName) {
state.useName = anotherName;
}
};
const actions = {