vuex 基础理解看这一篇就够了

vuex

定义

专为 Vue.js 应用程序开发的状态管理模式 ,扩展(vue是一套用于构建用户界面的渐进式框架,vue的数据驱动主要实现建立在三个对象上Dep、Watcher、Compiler)

对象作用
Dep主要负责依赖的收集
Compiler可以理解为 virtual dom + patch 也就是负责视图层的渲染
Watcher主要负责Dep和Compiler之间的联系

基础 es6 ,vuex

  1. mapGetters 辅助函数
    当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性
    官方示例:
// 在单独构建的版本中辅助函数为 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
    }
  })
}
  1. 对展开符运算
    mapState 函数返回的是一个对象。我们如何将它与局部计算属性混合使用呢?通常,我们需要使用一个工具函数将多个对象合并为一个,以使我们可以将最终对象传给 computed 属性。但是自从有了对象展开运算符,我们可以极大地简化写法:
computed: {
  localComputed () { /* ... */ },
  // 使用对象展开运算符将此对象混入到外部对象中
  ...mapState({
    // ...
  })
}
  1. vuex里面的基本快理解
作用
state单一状态树,每个应用将仅仅包含一个 store 实例。单一状态树让我们能够直接地定位任一 特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照。
module由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
getterVuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算
mutation更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数
actionAction 类似于 mutation,不同在于:Action 提交的是 mutation,而不是直接变更状态。Action 可以包含任意异步操作。

getter:

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 对象,你可以以属性的形式访问这些值:

// 调用
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]

Getter 也可以接受其他 getter 作为第二个参数:

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 也可以接受其他 getter 作为第二个参数
	doneTodosCount: (state, getters) => {
		return getters.doneTodos.length
	}
  }
})

// 调用
store.getters.doneTodosCount // -> 1

可以很容易地在任何组件中使用它:

computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}

通过方法访问
可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用

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 也可以接受其他 getter 作为第二个参数
	doneTodosCount: (state, getters) => {
		return getters.doneTodos.length
	},
	// 通过方法调用
	getTodoById: (state) => (id) => {
		return state.todos.find(todo => todo.id === id)
	}
  }
})

// 调用
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

mapGetters 辅助函数
mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性
官方代码示例:

import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}

如果你想将一个 getter 属性另取一个名字,使用对象形式:

...mapGetters({
  // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})

mutations:

const store = new Vuex.Store({
  state: {
    count: 1
  },
	getters: {
		getcount: state => {
			return state.todos.filter(todo => todo.done)
		}
	},
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})

不能直接调用一个 mutation handler。这个选项更像是事件注册:“当触发一个类型为 increment 的 mutation 时,调用此函数。”要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法:

// 调用
store.commit('increment')
store.getters.getcount // -> 2

提交载荷(Payload)
可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload):

const store = new Vuex.Store({
  state: {
    count: 1
  },
	getters: {
		getcount: state => {
			return state.todos.filter(todo => todo.done)
		}
	},
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    },
    // 提交载荷(Payload)
	increment00 (state, payload) {
		state.count += payload.amount
	}
  }
})
// 调用
store.commit("increment00",{amount: 10})

Mutation 必须是同步函数
一条重要的原则就是要记住 mutation 必须是同步函数。为什么?请参考下面的例子:

mutations: {
  someMutation (state) {
    api.callAsyncMethod(() => {
      state.count++
    })
  }
}

在组件中提交 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 ,不是直接改变状态:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment_mutations (state) {
      state.count++
    }
  },
  actions: {
    increment_actions (context) {
      context.commit('increment_mutations')
    }
  }
})

分发 Action
Action 通过 store.dispatch 方法触发分发操作:

store.dispatch('increment_actions')
store.state.count // -> 1

异步 以及 以 载荷的方式提交分发

	const store = new Vuex.Store({
		state: {
			count: 0
		},
		mutations: {
			increment_mutations (state) {
				state.count++
			}
		},
		actions: {
			increment_actions (context) {
				context.commit('increment_mutations')
			},
			// 异步提交 mutation
			incrementAsync ({ commit }) {
				setTimeout(() => {
					commit('increment_mutations')
				}, 1000)
			},
			// 以载荷形式分发
			store.dispatch('incrementAsync', {
				amount: 10
			})
		
			// 以对象形式分发
			store.dispatch({
				type: 'incrementAsync',
				amount: 10
			})
		}
	})

module:

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) {
			// 这里的 `state` 对象是模块的局部状态
			return state.count * 2
		},
		// 根节点状态会作为第三个参数暴露出来
	sumWithRootCount (state, getters, rootState) {
		return state.count + rootState.count
	}

	},
	actions: {
	// 通过 state 暴露出局部状态, rootState 是节点状态
		incrementIfOddOnRootSum ({ state, commit, rootState }) {
			if ((state.count + rootState.count) % 2 === 1) {
				commit('increment')
			}
		}
	}
}

命名空间:

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']
          }
        }
      }
    }
  }
})

在带命名空间的模块内访问全局内容(Global Assets)

如果你希望使用全局 state 和 getter,rootState 和 rootGetters 会作为第三和第四参数传入 getter,也会通过 context 对象的属性传入 action。

若需要在全局命名空间内分发 action 或提交 mutation,将 { root: true } 作为第三参数传给 dispatch 或 commit 即可。

modules: {
  foo: {
    namespaced: true,

    getters: {
      // 在这个模块的 getter 中,`getters` 被局部化了
      // 你可以使用 getter 的第四个参数来调用 `rootGetters`
      someGetter (state, getters, rootState, rootGetters) {
        getters.someOtherGetter // -> 'foo/someOtherGetter'
        rootGetters.someOtherGetter // -> 'someOtherGetter'
      },
      someOtherGetter: state => { ... }
    },

    actions: {
      // 在这个模块中, dispatch 和 commit 也被局部化了
      // 他们可以接受 `root` 属性以访问根 dispatch 或 commit
      someAction ({ dispatch, commit, getters, rootGetters }) {
        getters.someGetter // -> 'foo/someGetter'
        rootGetters.someGetter // -> 'someGetter'

        dispatch('someOtherAction') // -> 'foo/someOtherAction'
        dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'

        commit('someMutation') // -> 'foo/someMutation'
        commit('someMutation', null, { root: true }) // -> 'someMutation'
      },
      someOtherAction (ctx, payload) { ... }
    }
  }
}

模块动态注册
在 store 创建之后,你可以使用 store.registerModule 方法注册模块:

import Vuex from 'vuex'

const store = new Vuex.Store({ /* 选项 */ })

// 注册模块 `myModule`
store.registerModule('myModule', {
  // ...
})
// 注册嵌套模块 `nested/myModule`
store.registerModule(['nested', 'myModule'], {
  // ...
})

之后就可以通过 store.state.myModule 和 store.state.nested.myModule 访问模块的状态。

模块动态注册功能使得其他 Vue 插件可以通过在 store 中附加新模块的方式来使用 Vuex 管理状态。例如,vuex-router-sync 插件就是通过动态注册模块将 vue-router 和 vuex 结合在一起,实现应用的路由状态管理。

你也可以使用 store.unregisterModule(moduleName) 来动态卸载模块。注意,你不能使用此方法卸载静态模块(即创建 store 时声明的模块)。

注意,你可以通过 store.hasModule(moduleName) 方法检查该模块是否已经被注册到 store

总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值