Vuex 是Vue.js 应用程序的状态管理模式 + 库。它充当应用程序中所有组件的集中存储,其规则确保状态只能以可预测的方式改变。
使用 Vuex 并不意味着你应该把所有的状态都放在 Vuex 中。尽管将更多状态放入 Vuex 会使您的状态更改更加明确和可调试,但有时它也会使代码更加冗长和间接。如果一块状态严格属于单个组件,那么将其保留为本地状态就可以了。您应该权衡利弊并做出适合您应用程序开发需求的决定。
Vuex视频教学 有兴趣的可以看看
安装
npm
npm install vuex@next --save
yarn
yarn add vuex@next --save
State
存储在 Vuex 中的数据,类似data仓库
首先创建一个简单的Vuex仓库
import { createApp } from 'vue'
import { createStore } from 'vuex'
// 创建新的存储实例。
const store = createStore({
state () {
return {
count: 0
}
},
mutations: {
increment (state) {
state.count++
}
}
})
const app = createApp({ /* 您的根组件 */ })
// 将仓库实例作为插件安装
app.use(store)
在页面中使用
computed: {
count () {
return store.state.count //每次更改时,都会导致计算属性重新评估,并触发关联的 DOM 更新。
},
},
methods: {
increment() {
this.$store.commit('increment') //调用vuex中方法
console.log(this.count) // 1
}
}
上面这种方法虽然实用但是当组件需要使用多个存储状态属性或 getter 时,声明所有这些计算属性可能会变得重复和冗长。为了解决这个问题,我们可以使用mapState帮助器为我们生成计算的 getter 函数,来避免这些问题:
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
}
})
}
在页面中使用对象展开符将属性混合到外部对象中
computed: {
...mapState({
// ...
})
}
Getter
Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
有时候仓库中的数据并不完全是我们需要的,这时候我们会去过滤
//错误使用
无法直接修改仓库中的参数
doneTodosCount(){
this.$store.state.todos = this.$store.state.todos.map(e=> e.id);
}
// 正确使用
computed: {
doneTodosCount () {
return this.$store.state.todos.filter(todo => todo.done).length
}
}
如果有多个组件需要使用它,我们要么复制该函数,要么将其提取到共享帮助程序中并在多个位置导入——两者都不理想。Vuex 允许我们在 store 中定义“getter”。您可以将它们视为仓库的计算属性。
属性式访问
const store = createStore({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos (state) {
return state.todos.filter(todo => todo.done)
}
}
})
// 页面中属性式访问
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
方法式访问
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
//接受参数过滤
store.getters.getTodoById(2) //返回 -> { id: 2, text: '...', done: false }
mapGetters助手只是将存储getter映射到本地计算属性:
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
如果要将getter映射到其他名称,请使用对象:
...mapGetters({
// 将this.doneCount“指向`this.store.getters.doneTodosCount”
doneCount: 'doneTodosCount'
})
Mutations(同步)
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler) 。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数,并且在 Vuex 中,mutation 都是同步事务:
const store = createStore({
state: {
count: 1
},
mutations: {
increment (state) {
// mutate state
state.count++
}
}
})
//使用
store.commit('increment')
//类似传入increment 来触发 increment 这个函数
也可以向 store.commit 传入额外的参数
//state就是vuex仓库对象state 默认传入调用无需传入;
//n为触发方法时传入的参数 用于做一些操作;
mutations: {
increment (state, n) {
state.count += n
}
}
//使用
store.commit('increment', 10)
也可以使用对象方式提交 当然效果是一样的
store.commit({
type: 'increment',
amount: 10
})
使用常量替代 Mutation 事件类型
是否使用常量在很大程度上是一种偏好——它在有许多开发人员的大型项目中很有帮助,但如果你不喜欢它们,它完全是可选的。
// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// store.js
import { createStore } from 'vuex'
import { SOME_MUTATION } from './mutation-types'
const store = createStore({
state: { ... },
mutations: {
// we can use the ES2015 computed property name feature
// to use a constant as the function name
[SOME_MUTATION] (state) {
// mutate state
}
}
})
Action(异步)
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
让我们来注册一个简单的 action:
const store = createStore({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment ({commit}) {
commit('increment')
}
}
})
Action 通过 store.dispatch 方法触发:
store.dispatch('increment')
乍一眼看上去感觉多此一举,我们直接分发 mutation 岂不更方便?实际上并非如此,还记得 mutation 必须同步执行这个限制么?Action 就不受约束!我们可以在 action 内部执行异步操作:
actions: {
increment ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
Actions 支持同样的载荷方式和对象方式进行分发:
// 以载荷形式分发
store.dispatch('incrementAsync', {
amount: 10
})
// 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount: 10
})
接下来看一个购物车例子
actions: {
checkout ({ commit, state }, products) {
// 把当前购物车的物品备份起来
const savedCartItems = [...state.cart.added]
// 发出结账请求,然后乐观地清空购物车
commit(types.CHECKOUT_REQUEST)
// 购物 API 返回一个成功回调和一个失败回调
shop.buyProducts(
products,
// 成功触发
() => commit(types.CHECKOUT_SUCCESS),
// 失败触发
() => commit(types.CHECKOUT_FAILURE, savedCartItems)
)
}
}
组合 Action
Action 通常是异步的,那么如何知道 action 什么时候结束呢?更重要的是,我们如何才能组合多个 action,以处理更加复杂的异步流程?
首先,你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}
//页面触发
store.dispatch('actionA').then(() => {
// ...
})
如果我们利用 async / await 我们可以如下组合 action:
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}