Vuex
详细见:vuex官网
为什么用Vuex?
应用场景:当多个组件共享同一个属性时,该属性变化后,需要让每个组件根据该属性变化得到响应;
可用方法:
- 在父组件(或者祖辈组件)中定义该属性及修改方法,通过层层传递的方式,子组件可以获取更新后的属性,或者通过方法修改该属性;【缺点:层层嵌套,关系脆弱且复杂】
- 通过provide/inject方法,进行状态的管理,但是这种provide/inject方法一般适用于结构不算复杂,或者几个组件之间的状态共享,如果逻辑结构复杂,这种方法就不适用了;并且provide方法需要在组件中提供数据,而Vuex是独立在组件之外,只做状态管理用;
- 通过Vuex状态集中的方式,进行状态管理,然后通过dispatch方法去更新状态;
状态自管理
简单的状态自管理应用:
- state,驱动应用的数据源;
- view,以声明方式将 state 映射到视图;
- actions,响应在 view 上的用户输入导致的状态变化。
Vuex
当需要多个组件共享同一个状态,并且能够修改之,此时上面的单向数据流模式就不再适用;
store
Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:
Vuex的核心是store,该容器包含应用中大部分state状态,Vuex与全局对象不同点在于:
- Vuex中的状态是响应式的。当store中状态发生变化时,相应的组件也会得到高效更新;
- Vuex中状态不能够直接更新,改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。
// 如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
// 组件中修改状态
store.commit('increment')
console.log(store.state.count) // -> 1
state
Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。至此它便作为一个“唯一数据源”而存在。这也意味着,每个应用将仅仅包含一个 store 实例;
通过在根实例对象中注册store
选项,该store实例会注入到每个子组件中,子组件通过this.$store,即可访问到store中状态
// 根实例对象中注册store
const app = new Vue({
el: '#app',
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
store,
components: { Counter },
template: `
<div class="app">
<counter></counter>
</div>
`
})
///
// 子组件中访问store对象
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
mapState 辅助函数
当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 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
}
})
}
Getter
有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数。也就是将state中的状态进一步处理。相当于state的计算属性,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)
}
}
})
/
//组件中使用
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
mapGetter辅助函数
类似于mapState,当多个需要用到多个getter对应的属性时使用
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
Mutation
更改 Vuex
的 store
中的状态的唯一方法是提交 mutation
。Vuex
中的 mutation
非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)
。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数;
- 基本用法
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
// increment就是事件类型
increment (state) {
// 变更状态
state.count++
}
}
})
//调用mutation对应的方法:
store.commit('increment')
- 携带参数
// ...
mutations: {
increment (state, n) {
state.count += n
}
}
//
// 使用
store.commit('increment', 10)
- 对象形式携带参数
//store.js
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
//
// 调用
store.commit({
type: 'increment',
amount: 10
})
- 使用常量替代 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
}
}
})
// 调用
store.commit({
type: 'SOME_MUTATION',
amount: 10
})
mapMutations用法
你可以在组件中使用this.$store.commit('xxx')
提交mutation
,或者使用mapMutations
辅助函数将组件中的methods
映射为store.commit
调用(需要在根节点注入store
)
// 参数可以直接在addAge调用处传入
methods:{
...mapMutations(['addAge'])
}
// 等价于
methods:{
addAge(payLoad){
this.$store.commit('addAge',payLoad)
}
}
Action
Action 类似于 mutation,不同在于:
- Action 提交的是
mutation
,即通过commit
调用mutation
中方法,不是直接变更状态。 - Action 可以包含任意异步操作。
- 组件中使用
dispatch
方法调用Action中的方法,再通过mutation
修改状态 - 用于异步修改状态
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
// 组件中使用
store.dispatch('increment')
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')`
})
}
}
mapActions用法
与mapMutations
用法类似
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 对象就有可能变得相当臃肿。
为了解决以上问题,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 的状态
- 局部状态
const moduleA = {
state: { count: 0 },
mutations: {
increment (state) {
// 这里的 `state` 对象是模块的局部状态
state.count++
}
},
getters: {
doubleCount (state) {
return state.count * 2
}
}
}
// 可以接受rootState参数
actions: {
incrementIfOddOnRootSum ({ state, commit, rootState }) {
if ((state.count + rootState.count) % 2 === 1) {
commit('increment')
}
}
}
- 在带命名空间的模块内访问全局内容
如果你希望使用全局 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) { ... }
}
}
}
Vuex的核心概念和实现原理
- State: 提供一个响应式数据;
- Getter: 借助Vue的计算属性computed实现数据的缓存;
- Mutation:更改state方法;
- Action: diaptch方法,但最后还是需要出发mutation方法修改state值;
- Module: Vue.set动态添加到响应式数据中;
Vuex
底层代码简化版mini-Vuex
,助于理解
import Vue from 'vue'
const Store = function Store(options={}){
// 仍旧是通过new一个Vue实例,并且将state放在响应式数据中,以实现响应式更新
this._vm = new Vue({
data:{
$$state:state,
},
})
this._mutations = mutations;
}
// commit方法,通过调用mutations上的方法,更新state状态值
Store.prototype.commit = function(type,payload){
if(this._mutations[type]){
this._mutations[type](this.state,payload)
}
}
// 此处用到defineProperties方法重写this下的state值,
//使其获取的是上面new出来的state值,因此最后组件中state中的值,
//就是Vuex中new出来的响应式数据;
Object.defineProperties(Store.prototype,{
state:{
get:function(){
return this._vm._data.$$state
}
}
})
export defualt {Store}
现在使用上面简化版的mini-Vuex ,
注意:这里只是实现了简单的commit操作
// main.js
import Vue from 'vue'
import Vuex from './mini-vuex'
import App from './App.vue'
Vue.use(Vuex)
Vue.config.productionTip = false;
const store = new Vuex.Store({
state:{
count:0,
},
// 同步方法 使用commit方法去更新state
mutations:{
increment(state,n){
state.count+=n; // 执行点击加n的操作
}
},
// 直接将store挂载到Vue的原型上
Vue.prototype.$store = store
new Vue({
render:h=>h(App),
}).$mount('#app')