vue实践05之vuex
getter方法
有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数:
computed: {
doneTodosCount () {
return this.$store.state.todos.filter(todo => todo.done).length
}
}
复制代码
如果有多个组件需要用到此属性,我们要么复制这个函数,或者抽取到一个共享函数然后在多处导入它——无论哪种方式都不是很理想。
Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
- Getter 接受 state 作为其第一个参数:
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
add(state) {
state.count++;
},
reduce(state) {
state.count--;
}
},
getters: {
countAdd100: state => {
return state.count + 100
}
}
})
复制代码
- 在组件中引入getters
import { mapState, getters } from "vuex";
3. 在组件中访问getters
computed: {
countAdd1001() {
return this.$store.getters.countAdd100;
}
}
复制代码
- mapGetters 辅助函数
mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性,要求局部计算属性和getter中定义的方法名一样,类似mapState数组。
computed: {
...mapGetters([
"countAdd100"
])
}
复制代码
- 全部代码
- count.vue代码如下:
<template>
<div>
<h2>{{msg}}</h2>
<hr/>
<!--<h3>{{$store.state.count}}</h3>-->
<h6>{{countAdd100}}</h6>
<h6>{{countAdd1001}}</h6>
<div>
<button @click="$store.commit('add')">+</button>
<button @click="$store.commit('reduce')">-</button>
</div>
</div>
</template>
<script>
import store from "@/vuex/store";
import { mapState, getters, mapGetters } from "vuex";
export default {
data() {
return {
msg: "Hello Vuex"
};
},
computed: {
...mapGetters([
"countAdd100"
]),
countAdd1001() {
return this.$store.getters.countAdd100;
}
},
store
};
</script>
复制代码
- store.js代码
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
add(state) {
state.count++;
},
reduce(state) {
state.count--;
}
},
getters: {
countAdd100: state => {
return state.count + 100
}
}
})
export default store
复制代码
Mutation方法
- 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
复制代码
你不能直接调用一个 mutation handler。这个选项更像是事件注册:“当触发一个类型为 increment 的 mutation 时,调用此函数。”要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法:
store.commit('increment')
复制代码
- 提交载荷(Payload) 你可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload):
mutations: {
increment (state, n) {
state.count += n
}
}
store.commit('increment', 10)
复制代码
- 在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:
<button @click="$store.commit('incrementObj',{amount:100})">+100</button>
<button @click="$store.commit({type:'incrementObj',amount:1000})">+1000</button>
复制代码
Action
- action定义
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。 下面代码中
incrementAsync
模拟了一个异步操作。
actions: {
addAction({ commit }) {
commit("add")
},
reduceAction({ commit }) {
commit("reduce")
},
incrementAsync({ commit }) {
setTimeout(() => {
commit('add')
}, 1000)
}
}
复制代码
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。当我们在之后介绍到 Modules 时,你就知道 context 对象为什么不是 store 实例本身了。
mutation 必须同步执行这个限制么?Action 就不受约束!我们可以在 action 内部执行异步操作:
incrementAsync({ commit }) {
setTimeout(() => {
commit('add')
}, 1000)
}
复制代码
- dispactch方法调用action
在组件中调用action,代码如下:
methods: {
increment(){
this.$store.dispatch("addAction");
},
decrement() {
this.$store.dispatch("reduceAction")
},
incrementAsync() {
this.$store.dispatch("incrementAsync")
}
}
复制代码
- mapAactions方法调用action
首先引用mapActions,import { mapActions} from "vuex";
实例代码如下:
methods: {
...mapActions([
'addAction', // 将 `this.increment()` 映射为 `this.$store.dispatch('addAction')`
// `mapActions` 也支持载荷:
'reduceAction' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('reduceAction')`
]),
...mapActions({
asyncAdd: 'incrementAsync' // 将 `this.asyncAdd()` 映射为 `this.$store.dispatch('incrementAsync')`
})
}
复制代码
- 组合action
Action 通常是异步的,那么如何知道 action 什么时候结束呢?更重要的是,我们如何才能组合多个 action,以处理更加复杂的异步流程?
首先,你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:
定义action如下:
mutations: {
reduce(state) {
state.count--;
}
},
actions: {
actionA({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('reduce')
resolve()
}, 1000)
})
}
}
复制代码
组件中代码如下:
methods: {
decrement() {
this.$store.dispatch('actionA').then(() => {
console.log("先减1再加1")
this.incrementAsync()
})
},
incrementAsync() {
this.$store.dispatch("incrementAsync")
}
}
复制代码
module模块组
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
复制代码
命名空间
默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。
如果希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。例如:
const store = new Vuex.Store({
modules: {
account: {
namespaced: true,
// 模块内容(module assets)
state: { ... }, // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响
getters: {
isAdmin () { ... } // -> getters['account/isAdmin']
},
actions: {
login () { ... } // -> dispatch('account/login')
},
mutations: {
login () { ... } // -> commit('account/login')
},
// 嵌套模块
modules: {
// 继承父模块的命名空间
myPage: {
state: { ... },
getters: {
profile () { ... } // -> getters['account/profile']
}
},
// 进一步嵌套命名空间
posts: {
namespaced: true,
state: { ... },
getters: {
popular () { ... } // -> getters['account/posts/popular']
}
}
}
}
}
})
复制代码
上例中myPage和posts均是account的子module,但是myPage没有设置命名空间,所以myPage继承了account的命名空间。posts设置命名空间,所以在访问posts内部的getters时,需要添加全路径。
实际运行代码如下:
const moduleA = {
namespaced: true,
state: { count: 10 },
mutations: {
increment(state) {
// 这里的 `state` 对象是模块的局部状态
state.count++
}
},
getters: {
doubleCount(state) {
return state.count * 2
}
},
actions: {
incrementIfOddOnRootSum({ state, commit, rootState }) {
if ((state.count + rootState.count) % 2 === 1) {
commit('increment')
}
}
},
getters: {
sumWithRootCount(state, getters, rootState) {
return state.count + rootState.count
}
}
}
---在父节点中添加module定义
modules: {
a: moduleA
}
复制代码
在vue中访问定义的module
<button @click="$store.commit('a/increment')">double</button>
<button @click="doubleCount">doubleCount</button>
复制代码
methods方法定义:
count() {
return this.$store.state.a.count
},
doubleCount() {
return this.$store.commit('a/increment')
}
复制代码