截止博客发布前,Vuex 拥有 3.x 和 4.x 版本。
本文总结的是与 Vue 2 匹配的 Vuex 3 的使用。
更多操作请参考官方文档:https://v3.vuex.vuejs.org/
与 Vue 3 匹配的 Vuex 4 的文档: https://vuex.vuejs.org/
写过 vue 项目的程序员应该都知道父子组件传参的方式,通过子组件的 props 参数,和 $emit 来触发事件。
但是当遇到多个组件共享状态时,传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力,甚至会导致无法维护的代码。
基于此,把组件的共享状态抽取出来,以一个全局单例模式管理,vuex 就产生了。
Vue 2 的脚手架项目,安装 3.6.2版本。
npm install vuex@3.6.2 --save
在 src 目录下新建 store 文件夹,在该目录下新建 index.js
index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
count: 1
}
const getters = {
}
const mutations = {
add(state, n) {
state.count += n
},
reduce(state) {
state.count--
}
}
const actions = {
}
export default new Vuex.Store({
state,
getters,
mutations,
actions
})
入口文件引入
main.js
import store from './store'
new Vue({
el: '#app',
store,
components: {
App
},
template: ' '
})
通过 commit 提交 mutation 中的方法修改 state。
组件代码
<template>
<div>
<el-button @click="$store.commit('add', 1)">add