有时候咱们须要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数:html
computed: {
doneTodosCount () {
return this.$store.state.todos.filter(todo => todo.done).length
}
}
复制代码
若是有多个组件须要用到此属性,咱们要么复制这个函数,或者抽取到一个共享函数而后在多处导入它——不管哪一种方式都不是很理想。vue
Vuex 容许咱们在 store 中定义“getter”(能够认为是 store 的计算属性)。就像计算属性同样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被从新计算。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
}
}
})
复制代码
import { mapState, getters } from "vuex";
3. 在组件中访问getters数组
computed: {
countAdd1001() {
return this.$store.getters.countAdd100;
}
}
复制代码
computed: {
...mapGetters([
"countAdd100"
])
}
复制代码
<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>
复制代码
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
复制代码
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')
复制代码
mutations: {
increment (state, n) {
state.count += n
}
}
store.commit('increment', 10)
复制代码
<button @click="$store.commit('incrementObj',{amount:100})">+100</button>
<button @click="$store.commit({type:'incrementObj',amount:1000})">+1000</button>
复制代码
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 内部执行异步操做:bash
incrementAsync({ commit }) {
setTimeout(() => {
commit('add')
}, 1000)
}
复制代码
methods: {
increment(){
this.$store.dispatch("addAction");
},
decrement() {
this.$store.dispatch("reduceAction")
},
incrementAsync() {
this.$store.dispatch("incrementAsync")
}
}
复制代码
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')`
})
}
复制代码
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")
}
}
复制代码
因为使用单一状态树,应用的全部状态会集中到一个比较大的对象。当应用变得很是复杂时,store 对象就有可能变得至关臃肿。jsp
为了解决以上问题,Vuex 容许咱们将 store 分割成模块(module)。每一个模块拥有本身的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行一样方式的分割:async
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')
}
复制代码