Vuex有5个核心概念,分别是State
,Getters
,mutations
,Actions
,Modules
。
vue
Vuex
使用单一状态树,也就是说,用一个对象包含了全部应用层级的状态,做为惟一数据源而存在。没一个Vuex
应用的核心就是store
,store
可理解为保存应用程序状态的容器。store
与普通的全局对象的区别有如下两点:
(1)Vuex
的状态存储是响应式的。当Vue
组件从store
中检索状态的时候,若是store
中的状态发生变化,那么组件也会相应地获得高效更新。
(2)不能直接改变store
中的状态。改变store
中的状态的惟一途径就是显式地提交mutation
。这能够确保每一个状态更改都留下可跟踪的记录,从而可以启用一些工具来帮助咱们更好的理解应用
安装好Vuex
以后,就能够开始建立一个store
,代码以下:node
const store = new Vuex.Store({ // 状态数据放到state选项中 state: { counter: 1000, }, // mutations选项中定义修改状态的方法 // 这些方法接收state做为第1个参数 mutations: { increment(state) { state.counter++; }, }, });
在组件中访问store
的数据,能够直接使用store.state.count
。在模块化构建系统中,为了方便在各个单文件组件中访问到store
,应该在Vue
根实例中使用store
选项注册store
实例,该store
实例会被注入根组件下的所偶遇子组件中,在子组件中就能够经过this.$store
来访问store
。代码以下:vuex
new Vue({ el: "#app", store, })
若是在组件中要展现store
中的状态,应该使用计算属性来返回store
的状态,代码以下:数组
computed: { count(){ return this.$store.state.count } }
以后在组件的模板中就能够直接使用count
。当store
中count
发生改变时,组件内的计算属性count
也会同步发生改变。
那么如何更改store
中的状态呢?注意不要直接去修改count
的值,例如:缓存
methods: { handleClick(){ this.&store.state.count++; // 不要这么作 } }
既然选择了Vuex
做为你的应用的状态管理方案,那么就应该遵守Vuex
的要求;经过提交mutation
来更改store
中的状态。在严格模式下,若是store
中的状态改变不是有mutation
函数引发的,则会抛出错误,并且若是直接修改store
中的状态,Vue
的调试工具也没法跟踪状态的改变。在开发阶段,能够开启严格模式,以免字节的状态修改,在建立store
的时候,传入strict: true
代码以下:app
const store = new Vuex.Store({ strict: true })
Vuex
中的mutation
很是相似于事件:每一个mutation
都有一个字符串的事件类型和一个处理器函数,这个处理器函数就是实际进行状态更改的地方,它接收state
做为第1个参数。
咱们不能直接调用一个mutation
处理器函数,mutations
选项更像是事件注册,当触发一个类型为increment
的mutation
时,调用此函数。要调用一个mutation
处理器函数,须要它的类型去调用store.commit
方法,代码以下:异步
store.commit("increment")
假如在store
的状态中定义了一个图书数组,代码以下:async
export default new Vuex.Store({ state: { books: [ { id: 1, title: "Vue.js", isSold: false }, { id: 2, title: "common.js", isSold: true }, { id: 3, title: "node.js", isSold: true }, ], }, })
在组件内须要获得正在销售的书,因而定义一个计算属性sellingBooks
,对state
中的books
进行过滤,代码以下:模块化
computed: { sellingBooks(){ return this.$store.state.books.filter(book => book.isSold === true); } }
这没有什么问题,但若是是多个组件都须要用到sellingBooks
属性,那么应该怎么办呢?是复制代码,仍是抽取为共享函数在多处导入?显然,这都不理想
Vuex
容许咱们在store
中定义getters
(能够认为是store
的计算属性)。与计算属性同样,getter
的返回值会根据它的依赖项被缓存起来,且只有在它的依赖项发生改变时才会从新计算。
getter
接收state
做为其第1个参数,代码以下:函数
export default new Vuex.Store({ state: { books: [ { id: 1, title: "Vue.js", isSold: false }, { id: 2, title: "common.js", isSold: true }, { id: 3, title: "node.js", isSold: true }, ], }, getters: { sellingBooks(state) { return state.books.filter((b) => b.isSold === true); }, } })
咱们定义的getter
将做为store.getters
对象的竖向来访问,代码以下;
<h3>{{ $store.getters.sellingBooks }}</h3>
getter
也能够接收其余getter
做为第2个参数,代码以下:
getters: { sellingBooks(state) { return state.books.filter((b) => b.isSold === true); }, sellingBooksCount(state, getters) { return getters.sellingBooks.length; }, }
在组件内,要简化getter
的调用,一样可使用计算属性,代码以下:
computed: { sellingBooks() { return this.$store.getters.sellingBooks; }, sellingBooksCount() { return this.$store.getters.sellingBooksCount; }, },
要注意,做为属性访问的getter
做为Vue
的响应式系统的一部分被缓存。
若是想简化上述getter
在计算属性中的访问形式,可使用mapGetters
辅助函数。mapGetters
辅助函数仅仅是将 store
中的 getter
映射到局部计算属性:
import { mapGetters } from 'vuex' export default { // ... computed: { // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ "sellingBooks", "sellingBooksCount" ]), } }
若是你想将一个 getter
属性另取一个名字,使用对象形式:
...mapGetters({ // 把 `this.booksCount` 映射为 `this.$store.getters.sellingBooksCount` booksCount: 'sellingBooksCount' })
getter
还有更灵活的用法,用过让getter
返回一个函数,来实现给getter
传参。例如,下面的getter
根据图书ID来查找图书对象
getters: { getBookById(state) { return function (id) { return state.books.filter((book) => book.id === id); }; }, }
若是你对箭头函数已经掌握的炉火纯青,那么可使用箭头函数来简化上述代码
getters: { getBookById(state) { return (id) => state.books.filter((book) => book.id === id); },
下面在组件模板中的调用返回{ "id": 1, "title": "Vue.js", "isSold": false }
<h3>{{ $store.getters.getBookById(1) }}</h3>
上面已经介绍了更改store
中的状态的惟一方式是提交mutation
。
在使用store.commit
方法提交mutation
时,还能够传入额外的参数,即mutation
的载荷(payload),代码以下:
mutations: { increment(state, n) { state.counter+= n; }, }, store,commit("increment", 10)
载荷也能够是一个对象,代码以下:
mutations: { increment (state, payload) { state.count += payload.amount } } store.commit('increment', { amount: 10 })
提交mutation
时,也可使用包含type
属性的对象,这样传一个参数就能够了。代码以下所示:
store.commit({ type: "increment", amount: 10 })
当使用对象风格提交时,整个对象将做为载荷还给mutation
函数,所以处理器保持不变。代码以下:
mutations: { increment (state, payload) { state.count += payload.amount } }
在组件中提交mutation
时,使用的是this.$store.commit("increment")
,若是你以为这样比较繁琐,可使用mapMutations
辅助函数将组件中的方法映射为store.commit
调用,代码以下:
import { mapMutations } from "vuex"; methods: { ...mapMutations([ // 将this.increment()映射为this.$store.commit("increment") "increment", ]), }
除了使用字符串数组外,mapMutations
函数的参数也能够是一个对象
import { mapMutations } from "vuex"; methods: { ...mapMutations([ // 将this.add()映射为this.$store.commit("increment") add: "increment", ]), }
既然 Vuex
的 store
中的状态是响应式的,那么当咱们变动状态时,监视状态的 Vue
组件也会自动更新。这也意味着 Vuex
中的 mutation
也须要与使用 Vue
同样遵照一些注意事项:
1.最好提早在你的 store
中初始化好全部所需属性。
2.当须要在对象上添加新属性时,你应该
Vue.set(obj, 'newProp', 123)
, 或者state.obj = { ...state.obj, newProp: 123 }
咱们可使用常量来替代mutation
类型。能够把常量放到一个单独的JS文件中,有助于项目团队对store
中所包含的mutation
一目了然,例如:
// mutation-types.js export const INCREMENT = "increment"; // store.js import Vuex from "vuex"; import { INCREMENT } from "./mutation-types"; const store = new Vuex.Store({ state: { ... }, mutations: { // 咱们可使用 ES2015 风格的计算属性命名功能来使用一个常量做为函数名 [INCREMENT] (state) { // mutate 状态 } } })
在定义mutation
时,有一个重要的原则就是mutation
必须是同步函数,换句话说,在mutation
处理器函数中,不能存在异步调用,好比
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { setTimeout( () => { state.count++ }, 2000) } } })
在increment
函数中调用setTimeout()
方法在2s后更新count
,这就是一个异步调用。记住,不要这么作,由于这会让调试变得困难。假设正在调试应用程序并查看devtool
中的mutation
日志,对于每一个记录的mutation
,devtool
都须要捕捉到前一状态的快照。然而,在上面的例子中,mutation
中的setTimeout
方法中的回调让这不可能完成。由于当mutation
被提交的时候,回调函数尚未被调用,devtool
也没法知道回调函数何时真正被调用。实际上,任何在回调函数中执行的状态的改变都是不可追踪的。
若是确实须要执行异步操做,那么应该使用action
。action
相似于mutation
,不一样之处在于:
action
提交的是mutation
,而不是直接变动状态。action
能够包含任意异步操做一个简单的action
示例以下:
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { increment(context) { context.commit("increment"); }, }, })
Action
函数接受一个与 store
实例具备相同方法和属性的 context
对象,所以你能够调用 context.commit
提交一个 mutation
,或者经过 context.state
和 context.getters
来获取 state
和 getters
。甚至能够用context.dispatch
调用其余的action
。要注意的是,context
对象并非store
实例自己
若是在action
中须要屡次调用commit
,则能够考虑使用ECMAScript6
中的解构语法来简化代码,以下所示:
actions: { increment({ commit }) { commit("increment"); }, },
action
经过store.dispatch
方法触发,代码以下:
actions: { incrementAsync({ commit }) { setTimeout(() => { commit("increment"); }, 2000); }, },
action
一样支持载荷和对象方式进行分发。代码以下所示:
// 载荷是一个简单的值 store.dispatch("incrementAsync", 10) // 载荷是一个对象 store.dispatch("incrementAsync", { amount: 10 }) // 直接传递一个对象进行分发 store.dispatch({ type: "incrementAsync", amount: 10 })
在组件中可使用this.$store.dispatch("xxx")
分发action
,或者使用mapActions
辅助函数将组件的方法映射为store.dispatch
调用,代码以下:
// store.js const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ }, incrementBy(state, n){ state.count += n; } }, actions: { increment({ commit }) { commit("increment"); }, incrementBy({ commit }, n) { commit("incrementBy", n); }, }, }) // 组件 <template> <div id="app"> <button @click="incrementNumber(10)">+10</button> </div> </template> import { mapActions } from "vuex"; export default { name: "App", methods: { ...mapActions(["increment", "incrementBy"]), };
action
一般是异步的,那么如何知道action
什么时候完成呢?更重要的是,咱们如何才能组合多个action
来处理更复杂的异步流程呢?
首先,要知道是store.dispatch
能够处理被触发的action
的处理函数返回的Promise
,而且store.dispatch
仍旧返回Promise
,例如:
actionA({ commit }) { return new Promise((resolve, reject) => { setTimeout(() => { commit("increment"); resolve(); }, 1000); }); },
如今能够:
store.dispatch("actionA").then(() => { ... })
在另一个action
中也能够
actions: { //... actionB({dispatch, commit}) { return dispatch("actionA").then(() => { commit("someOtherMutation") }) } }
最后,若是咱们利用 async / await (opens new window)
,咱们能够以下组合 action
:
// 假设 getData() 和 getOtherData() 返回的是 Promise actions: { async actionA ({ commit }) { commit('gotData', await getData()) }, async actionB ({ dispatch, commit }) { await dispatch('actionA') // 等待 actionA 完成 commit('gotOtherData', await getOtherData()) } }
因为使用单一状态树,应用的全部状态会集中到一个比较大的对象。当应用变得很是复杂时,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 的状态
对于模块内部的 mutation
和 getter
,接收的第一个参数是模块的局部状态对象。
const moduleA = { state: () => ({ count: 0 }), mutations: { increment (state) { // 这里的 `state` 对象是模块的局部状态 state.count++ } }, getters: { doubleCount (state) { return state.count * 2 } } }
一样,对于模块内部的 action
,局部状态经过 context.state
暴露出来,根节点状态则为 context.rootState
:
const moduleA = { // ... actions: { incrementIfOddOnRootSum ({ state, commit, rootState }) { if ((state.count + rootState.count) % 2 === 1) { commit('increment') } } } }
对于模块内部的 getter
,根节点状态会做为第三个参数暴露出来:
const moduleA = { // ... getters: { sumWithRootCount (state, getters, rootState) { return state.count + rootState.count } } }
Vuex
并不限制你的代码结构。可是,它规定了一些须要遵照的规则:
1.应用层级的状态应该集中到单个 store
对象中。
2.提交 mutation
是更改状态的惟一方法,而且这个过程是同步的。
3.异步逻辑都应该封装到 action
里面。
只要你遵照以上规则,如何组织代码随你便。若是你的 store
文件太大,只需将 action
、mutation
和 getter
分割到单独的文件。
对于大型应用,咱们会但愿把 Vuex
相关代码分割到模块中。下面是项目结构示例:
└── store ├── index.js # 咱们组装模块并导出 store 的地方 ├── actions.js # 根级别的 action ├── mutations.js # 根级别的 mutation └── modules ├── cart.js # 购物车模块 └── products.js # 产品模块