-
Vuex概念:专门再Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读\x写),也是一种组件间通信的方式,适合任意的组件间的通信。
一般在什么场景使用:多组件共享数据 多组件依赖于同一个状态 来自不同组件的行为要改变同一个状态。
附上原理图:
2.搭建Vuex环境:
(1)创建文件:src/store/index.js
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)
//准备actions对象——响应组件中用户的动作
const actions = {}
//准备mutations对象——修改state中的数据
const mutations = {}
//准备state对象——保存具体的数据
const state = {}
//创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state
})
(2)在main.js中创建vm时传入store配置项`
//引入store
import store from './store'
......
//创建vm
new Vue({
el:'#app',
render: h => h(App),
store
})
3.基本的使用
- 初始化数据、配置
actions、配置Mutations,操作文档store.js
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//引用Vuex
Vue.use(Vuex)
const actions = {
//响应组件中加的动作
jia(context,value){
// console.log('actions中的jia被调用了',miniStore,value)
context.commit('JIA',value)
},
}
const mutations = {
//执行加
JIA(state,value){
// console.log('mutations中的JIA被调用了',state,value)
state.sum += value
}
}
//初始化数据
const state = {
sum:0
}
//创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state,
})
-
组件中读取vuex中的数据:
$store.state.sum -
组件中修改vuex中的数据:
$store.dispatch('action中的方法名',数据)或$store.commit('mutations中的方法名',数据)备注:若没有网络请求或其他业务逻辑,组件中也可以越过actions,即不写
dispatch,直接编写commit
getters的使用:当state中的数据需要经过加工后再使用时,可以使用getters加工。
如下:在store.js中添加配置:
const getters = { //同actions、mutations等
bigSum(state){
return state.sum * 10
}
}
//创建并暴露store
export default new Vuex.Store({
......
getters
})
记录于2022/03/12