Vue.js 学习笔记十五:Vuex 之 Vuex 核心概念和项目结构

目录

Vuex 核心概念

State

Getters

Mutations

Actions

Modules

项目结构


Vuex 核心概念

Vuex 有几个比较核心的概念。

  • state 存放状态

  • mutations state成员操作

  • getters 加工 state 成员给外界

  • actions 异步操作

  • modules 模块化状态管理

State

Vuex 使用单一状态树。是的,用一个对象就包含了全部的应用层级状态。至此它便作为一个“唯一数据源 ”而存在。这也意味着,每个应用将仅仅包含一个 store 实例。单一状态树让我们能够直接地定位任一特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照。

Getters

getters 是 store 的计算属性,对 state 的加工,是派生出来的数据。就像 computed 计算属性一样,getter 返回的值会根据它的依赖被缓存起来,且只有当它的依赖值发生改变才会被重新计算。

比如下面的 Store 中:

const store = new Vuex.Store({
  state: {
		goods: [
			{id: 1, name: 'goods1', price: 20},
			{id: 2, name: 'goods2', price: 80},
			{id: 3, name: 'goods3', price: 50},
		]
  }
})

要求筛选价格大于 40 的商品。

使用 computed 计算属性:

	computed: {
		searchGoods() {
			return this.$store.state.goods.filter(g => g.price > 40)
		}
	}

如果有多个组件需要用到此属性,我们要么复制这个函数,或者抽取到一个共享函数然后在多处导入它,无论哪种方式都不是很理想。

我们可以在 Store 中定义 getters:

const store = new Vuex.Store({
  state: {
		goods: [
			{id: 1, name: 'goods1', price: 20},
			{id: 2, name: 'goods2', price: 80},
			{id: 3, name: 'goods3', price: 50},
		]
  },
	getters: {
        // 接受 state 作为其第一个参数
		searchGoods: state => {
			return state.goods.filter(g => g.price > 50)
		}
	}
})

Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值。

<h1>{{ $store.getters.searchGoods }}</h1>

上面已经筛选出了结果,现在我要获取有多少数据呢?

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

const store = new Vuex.Store({
  state: {
		goods: [
			{id: 1, name: 'goods1', price: 20},
			{id: 2, name: 'goods2', price: 80},
			{id: 3, name: 'goods3', price: 50},
		]
  },
	getters: {
        // 接受 state 作为其第一个参数
		searchGoods: state => {
			return state.goods.filter(g => g.price > 50)
		},
		searchGoodsCount: (state, getters) => {
			return getters.searchGoods.length
		}
	}
})

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

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

getters 默认是不能传递参数的,如果希望传递参数,那么只能让 getters 本身返回另一个函数。

比如上面的案例中,我们希望根据 id 获取商品的信息:

const store = new Vuex.Store({
  state: {
		goods: [
			{id: 1, name: 'goods1', price: 20},
			{id: 2, name: 'goods2', price: 80},
			{id: 3, name: 'goods3', price: 50},
		]
  },
	getters: {
        // 接受 state 作为其第一个参数
		searchGoods: state => {
			return state.goods.filter(g => g.price > 50)
		},
		searchGoodsCount: (state, getters) => {
			return getters.searchGoods.length
		},
		searchById: (state) => (id) => {
			return state.goods.find(g => g.id === id)
		}
	}
})
<h1>{{ $store.getters.searchById(1) }}</h1>

Mutations

mutations 提交更改数据,使用 store.commit 方法更改 state 存储的状态(mutations同步函数)。

mutations 主要包括两部分:

字符串的事件类型(type)

一个回调函数(handler),该回调函数的第一个参数就是 state。

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})

而在组件中,我们需要这样去调用这个 mutation:

this.$store.commit('increment')

提交载荷(Payload)

在通过 mutation 更新数据的时候,有可能我们希望携带一些额外的参数。

我们可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload)

// ...
mutations: {
  increment (state, n) {
    state.count += n
  }
}
store.commit('increment', 10)

当需要多参提交时,推荐把他们放在一个对象中来提交:

// ...
mutations: {
  increment (state, payload) {
    state.count += payload.count
  }
}
store.commit('increment', {
  count: 10
})

对象风格的提交方式

上面的通过 commit 进行提交是一种普通的方式,Vue 还提供了另外一种风格, 它是一个包含 type 属性的对象:

store.commit({
  type: 'increment',
  count: 10
})

当使用这种对象风格的提交方式,整个对象都作为载荷传给 mutation 函数,因此 handler 保持不变。

Mutation 需遵守 Vue 的响应规则

既然 Vuex 的 store 中的状态是响应式的,那么当我们变更状态时,监视状态的 Vue 组件也会自动更新。这也意味着 Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项:

  1. 最好提前在你的 store 中初始化好所有所需属性。

  2. 当需要在对象上添加新属性时,你应该使用 Vue.set(obj, 'newProp', 123),或者以新对象替换老对象。例如,利用对象展开运算符 (opens new window)我们可以这样写:

state.obj = { ...state.obj, newProp: 123 }

示例:

const store = new Vuex.Store({
	state: {
		myInfo: {
			name: 'stary',
			age: 18
		}
	},
	mutations: {
		updateMyInfo(state, payload) {			
			// 方式一
			// Vue.set(state.myInfo, 'height', payload.height)
			// 方式二
			state.myInfo = {
				...state.myInfo,
				height: payload.height
			}
		}
	}
})

使用常量替代 mutation 事件类型

在 mutation 中,我们定义了很多事件类型(也就是其中的方法名称)。当我们的项目增大时,Vuex 管理的状态越来越多, 需要更新状态的情况越来越多,那么意味着 Mutation 中的方法越来越多。

方法过多,使用者需要花费大量的经历去记住这些方法,甚至是多个文件间来回切换,查看方法名称,甚至如果不是复制的时候,可能还会出现写错的情况。

在各种 Flux 实现中,一种很常见的方案就是使用常量替代 Mutation 事件的类型。

我们可以将这些常量放在一个单独的文件中, 方便管理以及让整个 app 所有的事件类型一目了然。

我们可以创建一个文件: mutation-types.js,并且在其中定义我们的常量。

定义常量时,我们可以使用 ES2015 中的风格,使用一个常量来作为函数的名称。

src/store/mutation-types.js

export const UPDATE_MY_INFO = 'UPDATE_MY_INFO'

src/store/index.js

import Vuex from 'vuex'
import { UPDATE_MY_INFO } from './mutation-types'

const store = new Vuex.Store({
	state: {
		myInfo: {
			name: 'stary',
			age: 18
		}
	},
	mutations: {
		[UPDATE_MY_INFO](state, payload) {			
			// 方式一
			// Vue.set(state.myInfo, 'height', payload.height)
			// 方式二
			state.myInfo = {
				...state.myInfo,
				height: payload.height
			}
		}
	}
})

src/components/HelloWorld.vue

<script>
import { UPDATE_MY_INFO } from './../store/mutation-types'
export default {
  name: 'HelloWorld',
	methods: {
		updateMyInfo() {			
			this.$store.commit(UPDATE_MY_INFO, {height: 180})
		}
	}
}
</script>

Mutation 必须是同步函数

Vuex 要求我们 Mutation 中的方法必须是同步方法。

比如下面的例子:

	mutations: {
		[UPDATE_MY_INFO](state, payload) {
			setTimeout(() => {
				state.myInfo = {
					...state.myInfo,
					height: payload.height
				}				
			}, 1000)						
		}
	}

现在想象,我们正在 debug 一个 app 并且观察 devtool 中的 mutation 日志。每一条 mutation 被记录,devtools 都需要捕捉到前一状态和后一状态的快照。然而,在上面的例子中 mutation 中的异步函数中的回调让这不可能完成:因为当 mutation 触发的时候,回调函数还没有被调用,devtools 不知道什么时候回调函数实际上被调用。实质上任何在回调函数中进行的状态的改变都是不可追踪的。

Actions

actions 像一个装饰器,提交 mutation,而不是直接变更状态(actions 可以包含任何异步操作)。

我们强调,不要在 Mutation 中进行异步操作。但是某些情况,我们确实希望在 Vuex 中进行一些异步操作,比如网络请求,必然是异步的。

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.statecontext.getters 来获取 state 和 getters。

但是注意, 这里它们并不是同一个对象,后面 Modules 的时候,再具体说。

实践中,我们会经常用到 ES2015 的 参数解构来简化代码(特别是我们需要调用 commit 很多次的时候):

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}

分发 Action

在 Vue 组件中,如果我们调用 action 中的方法,那么就需要使用 store.dispatch

store.dispatch('increment')

乍一眼看上去感觉多此一举,我们直接分发 mutation 岂不更方便?实际上并非如此,还记得 mutation 必须同步执行这个限制么?Action 就不受约束!我们可以在 action 内部执行异步操作:

actions: {
  increment ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}

Actions 支持同样的载荷方式和对象方式进行分发:

// 以载荷形式分发
store.dispatch('increment', {
  amount: 10
})

// 以对象形式分发
store.dispatch({
  type: 'increment',
  amount: 10
})

组合 Action

Action 通常是异步的,那么如何知道 action 什么时候结束呢?更重要的是,我们如何才能组合多个 action,以处理更加复杂的异步流程?

首先,你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}

现在你可以:

actions: {
  // ...
  actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => {
      commit('someOtherMutation')
    })
  }
}

最后,如果我们利用 async / await,我们可以如下组合 action:

// 假设 getData() 和 getOtherData() 返回的是 Promise

actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}

Modules

当项目庞大,状态非常多时,可以采用模块化管理模式。Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 statemutationactiongetter、甚至是嵌套子模块,从上至下进行同样方式的分割。

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 的状态

Module局部状态

对于模块内部的 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 相关代码分割到模块中。下面是项目结构示例:

├── index.html
├── main.js
├── api
│   └── ... # 抽取出API请求
├── components
│   ├── App.vue
│   └── ...
└── store
    ├── index.js          # 我们组装模块并导出 store 的地方
    ├── actions.js        # 根级别的 action
    ├── mutations.js      # 根级别的 mutation
    └── modules
        ├── cart.js       # 购物车模块
        └── products.js   # 产品模块

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

stary1993

你的鼓励是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值