Vuex
安装使用
在main.js同级目录下添加store文件夹,文件夹下新建index.js文件.index.js代码如下所示
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
//要设置的全局访问的state对象
const state = {
count1: 1,
count2: 2
};
const store = new Vuex.Store({
state
});
export default store;
在main.js中引入store的文件,再根实例注册之后,就可以在所有的子组件中读取状态了
// NPM
npm install vuex --save
// 使用
import Vue from 'vue'
import Vuex from 'vuex'
//引入index.js
import store from './store'
Vue.use(Vuex)
new Vue({
el: '#app',
router,
store, //使用store
template: '<App/>',
components: { App }
})
state
上述通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this. s t o r e 访 问 到 , 例 如 t h i s . store 访问到,例如this. store访问到,例如this.store.state.count1
export default {
name: 'App',
components:{
},
data(){
return {
}
},
computed:{
count () {
return this.$store.state.count
}
}
}
还可以借助 mapState 辅助函数帮助生成计算属性
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
export default {
name: 'App',
components:{
},
data(){
return {
}
},
computed:{
//这里的...是超引用,ES6的语法,意思是state里有多少属性值我可以在这里放多少属性值
...mapState({
count1 : state => state.count1,
count2 : state => state.count2,
//简写
count1,
count2
}),
}
}
getter
有时需要从 store 中的 state 中计算一些状态,例如求和.可以向下面这样求和,但是当这种状态需求很多时,这段代码需要写很多遍.这个时候就用到getter了.
computed: {
addCount () {
return this.$store.count1 + this.$store.count2
}
}
同样在store文件夹下的index.js文件添加如下代码.
const getters = {
addCount: state => {
return state.count1 + state.count2
}
}
// 也可以接受其他getter作为参数,例如 addCount: (state, getters) => {}
const store = new Vuex.Store({
state,
getters
});
这样的话开始的那段代码就可以这样写了
computed: {
addCount () {
return this.$store.getters.addCount
}
}
上述是通过属性访问,这种方式会缓存在系统中,只有当依赖的值变了,才会重新计算.
getter还可以通过方法访问,通过方法访问时,每次调用都会执行,而不会缓存结果.例如当需要传参和state里的值求和时
const getters = {
addCount: state => {
return state.count1 + state.count2
},
numAddCount: (state) => (num) => {
return num + state.count1 + state.count2
}
}
// 调用
this.$store.getters.numAddCount(3)
还可以用 mapGetters 辅助函数映射 getters 到计算属性
import { mapGetters } from 'vuex'
export default {
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
// 把 this.doneTodosCount 就等于 this.$store.getters.doneTodosCount
...mapGetters([
'addCount',
'numAddCount'
]),
// 如果想自定义的话,也可以这样
...mapGetters({
add: 'addCount',
numAdd: 'numAddCount'
})
}
}
Mutation
更改vuex中store的状态的方法是提交mutation.在store中定义mutations
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
这样可以在组件中使用 this.$store.commit(‘increment’)
还可以向 this.$store.commit 传入额外的参数,即 mutation 的 载荷(payload):
mutations: {
increment (state, n) {
state.count += n
}
}
在组件中使用 this.$store.commit(‘increment’, 10)
在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
})
值得注意的是,mutation必须是同步函数。
还可以使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。
import { mapMutations } from 'vuex'
export default {
methods: {
...mapMutations([
'increment', // 将 this.increment() 映射为 this.$store.commit('increment')
// mapMutations 也支持载荷:
'incrementBy' // 将 this.incrementBy(amount) 映射为 this.$store.commit('incrementBy', amount)
]),
...mapMutations({
add: 'increment' // 将 this.add() 映射为 this.$store.commit('increment')
})
}
}
Action
action类似于mutation,action提交的是mutation,action可以包含任何的异步操作。
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
// action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以
// 调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters
actions: {
increment ( context) {
context.commit('increment')
}
}
})
action也可以这么写
actions: {
increment ({commit, state}) {
commit('increment')
}
}
在组件中用this.$store.dispatch(‘increment’)来触发action
Actions 支持同样的载荷方式和对象方式进行分发
同样可以用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用:
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
'increment', // 将 this.increment() 映射为 this.$store.dispatch('increment')
// mapActions 也支持载荷:
'incrementBy' // 将 this.incrementBy(amount) 映射为 this.$store.dispatch('incrementBy', amount)
]),
...mapActions({
add: 'increment' // 将 this.add() 映射为 this.$store.dispatch('increment')
})
}
}
Module
当应用非常复杂时,store对象会变得很臃肿.此时需要用module来划分不同的模块。
const moduleA = {
state: { count: 0 },
mutations: {
increment (state) {
// 这里的 `state` 对象是模块的局部状态
state.count++
}
},
getters: {
doubleCount (state, rootState) {
return state.count * 2
}
},
actions: {
// 对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState
incrementIfOddOnRootSum ({ state, commit, rootState }) {
if ((state.count + rootState.count) % 2 === 1) {
commit('increment')
}
}
}
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
state: {
},
getters: {
},
mutations: {
},
actions: {
},
modules: {
a: moduleA,
b: moduleB
}
})
通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。
modules: {
A: {
namespaced: true,
getters: {
// 在这个模块的 getter 中,getters 被局部化了
// 使用rootState 和 rootGetters 访问根部state和getter
someGetter (state, getters, rootState, rootGetters) {
getters.someOtherGetter // -> 'A/someOtherGetter'
rootGetters.someOtherGetter // -> 'someOtherGetter'
},
someOtherGetter: state => { ... }
},
actions: {
// 在这个模块中, dispatch 和 commit 也被局部化了
// 他们可以接受 `root` 属性以访问根 dispatch 或 commit
someAction ({ dispatch, commit, getters, rootGetters }) {
getters.someGetter // -> 'A/someGetter'
rootGetters.someGetter // -> 'someGetter'
dispatch('someOtherAction') // -> 'A/someOtherAction'
dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'
commit('someMutation') // -> 'A/someMutation'
commit('someMutation', null, { root: true }) // -> 'someMutation'
},
someOtherAction (ctx, payload) { ... },
// 在带命名空间的模块注册全局 action,添加 root: true,并将这个 action 的定义放在函数 handler 中
actionOne: {
root: true,
handler (namespacedContext, payload) { ... } // -> 'someAction'
}
}
}
}
在组件中使用map辅助函数绑定带命名空间的模块时,可以将模块的空间名称字符串作为第一个参数传递给函数,这样所有绑定都会自动将该模块作为上下文.
computed: {
...mapState('A/module', {
a: state => state.a,
b: state => state.b
})
},
methods: {
...mapActions('A/module', [
'foo', // -> this.foo()
'bar' // -> this.bar()
])
}