官方文档git
vuex 使用单一状态树——是的,用一个对象就包含了所有的应用层级状态。github
// 建立一个 Counter 组件,在computed中返回。 const Counter = { template: `<div>{{ count }}</div>`, computed: { count () { //vuex的状态存储是响应式的 return store.state.count } } }
咱们可使用 mapState 辅助函数帮助咱们生成计算属性,将组件中的computed属性映射为 store 中的 statevuex
// 在单独构建的版本中辅助函数为 Vuex.mapState import { mapState } from 'vuex' export default { // ... computed: mapState({ // 箭头函数可以使代码更简练 count: state => state.count, // 传字符串参数 'count' 等同于 `state => state.count` countAlias: 'count', // 为了可以使用 `this` 获取局部状态,必须使用常规函数 countPlusLocalState (state) { return state.count + this.localCount } }) }
当映射的计算属性的名称与 state 的子节点名称相同时,咱们也能够给 mapState 传一个字符串数组。数组
computed: mapState([ // 映射 this.count 为 store.state.count 'count' ])
Vuex 容许咱们在 store 中定义“getter”(能够认为是 store 的计算属性)。就像计算属性同样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被从新计算。缓存
Getter 接受 state 做为其第一个参数:babel
const store = new Vuex.Store({ state: { todos: [ { id: 1, text: '...', done: true }, { id: 2, text: '...', done: false } ] }, getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) } } })
Getter 会暴露为 store.getters 对象:app
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
Getter 也能够接受其余 getter 做为第二个参数:异步
getters: { // ... doneTodosCount: (state, getters) => { return getters.doneTodos.length } } store.getters.doneTodosCount // -> 1
咱们能够很容易地在任何组件中使用它:ide
computed: { doneTodosCount () { return this.$store.getters.doneTodosCount } }
你也能够经过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时很是有用。
getters: { // ... getTodoById: (state) => (id) => { return state.todos.find(todo => todo.id === id) } } store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
咱们可使用 mapGetter 辅助函数帮助咱们生成计算属性,将组件中的computed属性映射为 store 中的 getter
import { mapGetters } from 'vuex' export default { // ... computed: { // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) } }
若是你想将一个 getter 属性另取一个名字,使用对象形式:
mapGetters({ // 映射 `this.doneCount` 为 `store.getters.doneTodosCount` doneCount: 'doneTodosCount' })
更改 Vuex 的 store 中的状态的惟一方法是提交 mutation。Vuex 中的 mutation 很是相似于事件:每一个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是咱们实际进行状态更改的地方,而且它会接受 state 做为第一个参数:
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state) { // 变动状态 state.count++ } } })
当触发一个类型为 increment 的 mutation 时,调用此函数。”要唤醒一个 mutation handler,你须要以相应的 type 调用 store.commit 方法:
store.commit('increment')
1.传入额外的参数,即 mutation 的 载荷(payload):
// ... mutations: { increment (state, n) { state.count += n } } store.commit('increment', 10)
2.载荷是一个对象
// ... mutations: { increment (state, payload) { state.count += payload.amount } } store.commit('increment', { amount: 10 })
提交 mutation 的另外一种方式是直接使用包含 type 属性的对象:
mutations: { increment (state, payload) { state.count += payload.amount } } store.commit({ type: 'increment', amount: 10 })
这样可使 linter 之类的工具发挥做用,同时把这些常量放在单独的文件中可让你的代码合做者对整个 app 包含的 mutation 一目了然:
// mutation-types.js export const SOME_MUTATION = 'SOME_MUTATION' // store.js import Vuex from 'vuex' import { SOME_MUTATION } from './mutation-types' const store = new Vuex.Store({ state: { ... }, mutations: { // 咱们可使用 ES2015 风格的计算属性命名功能来使用一个常量做为函数名 [SOME_MUTATION] (state) { // mutate state } } })
注意:一条重要的原则就是要记住 mutation 必须是同步函数。
你能够在组件中使用 this.$store.commit('xxx') 提交 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 相似于 mutation,不一样在于:
让咱们来注册一个简单的 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。
Action 经过 store.dispatch 方法触发:
store.dispatch('increment')
显然直接分发mutation更方便,可是mutation 必须同步执行,Action 则不受这个限制
咱们能够在action内部执行异步操做
actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }
Actions 支持一样的载荷方式和对象方式进行分发:
// 以载荷形式分发 store.dispatch('incrementAsync', { amount: 10 }) // 以对象形式分发 store.dispatch({ type: 'incrementAsync', amount: 10 })
你在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的methods映射为 store.dispatch 调用(须要先在根节点注入 store):
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')` }) } }
因为使用单一状态树,应用的全部状态会集中到一个比较大的对象。当应用变得很是复杂时,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 } } }
以menu为了分析下思路
1.app.js
import 'babel-polyfill' import Vue from 'vue' import App from './components/App.vue' import store from './store' //步骤1 import { currency } from './currency' Vue.filter('currency', currency) new Vue({ el: '#app', store, //步骤2 render: h => h(App) })
作了两步 : 引入store 并绑定到根实例上
2.store/index.js
import Vue from 'vue' import Vuex from 'vuex' import * as actions from './actions' import * as getters from './getters' import fruit from './modules/fruit'; Vue.use(Vuex) const store = new Vuex.Store({ actions, getters, modules: { fruit, }, }) export default store;
3.store/nutation-types.js
export const FRUIT_SHOW = "FRUIT_SHOW" export const FRUIT_HIDE = "FRUIT_HIDE"
4.store/modules/fruit.js
import {FRUIT_SHOW,FRUIT_HIDE,} from '../../store/mutation-types' export default { state: { appearence: false, }, mutations: { [FRUIT_HIDE](state) { state.appearence = false }, [FRUIT_SHOW](state) { state.appearence = true }, }, actions: { hideFruit({commit}) { commit(FRUIT_HIDE) }, showFruit({commit}) { commit(FRUIT_SHOW) }, }, getters: { fruitState:state => state.appearence, } }
5.使用方法
<template> <div> <p v-if="appearence">apple</p> <el-button type="primary" @click="showApple">显示</el-button> <el-button @click="hideApple">隐藏</el-button> </div> </template>
<script> import { mapState } from 'vuex'; import { mapGetters } from 'vuex'; export default { data () { return { } }, methods: { showApple(){ //使用commit触发mutations this.$store.commit('FRUIT_SHOW'); //使用dispatch触发actions,action中使用commit触发mutations //this.$store.dispatch('showFruit'); }, hideApple(){ //this.$store.commit('FRUIT_HIDE'); this.$store.dispatch('hideFruit'); }, }, //使用getters computed: mapGetters({ appearence: 'fruitState', }), /** //使用 state computed: mapState({ //appearence: appearence, 这样是错误,少了一层fruit appearence: state => state.fruit.appearence, }), //另外一种表示方法 computed:{ ...mapState({ appearence: state => state.fruit.appearence, }) }, **/ mounted() { //使用state获取状态 console.log(this.$store.state.fruit.appearence); //使用getters获取状态 console.log(this.$store.getters.fruitState); }, } </script>
6.另外一种定义getters的方法
store/modules/fruit.js
import { FRUIT_SHOW, FRUIT_HIDE, } from '../../store/mutation-types' export default { state: { appearence: false, }, mutations: { [FRUIT_HIDE](state) { state.appearence = false }, [FRUIT_SHOW](state) { state.appearence = true }, }, actions: { hideFruit({commit}) { commit(FRUIT_HIDE) }, showFruit({commit}) { commit(FRUIT_SHOW) }, }, //这里不在定义getters }
store/getters.js
const fruitState = (state) => state.fruit.appearence; export { fruitState, }