Vuex
5.1.1 Vuex简介
1.vuex 是什么
(1).概念:专门在 Vue 中实现集中式状态(数据)管理的一个 Vue 插件,对 vue 应 用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方 式,且适用于任意组件间通信。
(2).Github 地址: https://github.com/vuejs/vuex
2.什么时候使用 Vuex
(1)多个组件依赖于同一状态
(2)来自不同组件的行为需要变更同一状态
5.1.2 Vuex环境搭建
1.安装vuex
安装:npm i vuex@3
ps: vue2 安装 vuex3 ;vue3 安装 vuex4
2.创建store文件
(1).创建文件:src/store/index.js
//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//使用vuex
Vue.use(Vuex)
//准备actions--用于响应组件中的动作
const actions = {}
//准备mutation--用于操作数据(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'
......
new Vue({
el:'#app',
render:h=>h(App),
store
})
5.1.3 Vuex工作原理图
5.1.4 求和案例–vuex版
5.2 Vuex中的配置项
5.2.1 getters配置项
1.概念:当state中的数据需要经过加工后再使用时,可以使用getters加工
2.在store.js
中追加getters
配置
.........
//准备getters--用于将state中的数据进行加工
const getters = {
bigSum(state){
return state.sum*10
}
}
//暴露并创建store
export default new Vuex.Store({
......
getters
})
3.组件中读取数据:$store.getter.bigSum
5.2.2 mapState 与 mapGetters
1.mapState:帮助我们映射state
中的数据为计算属性
2.mapGetters: 帮助我们映射getters
中的数据为计算属性
computed: {
//靠mapState函数来实现上面的代码(对象写法)
...mapState({ sum: 'sum', school: 'school', subject: 'subject' }),
//靠mapState函数来实现上面的代码(数组写法:可以简写)
...mapState(['sum', 'school', 'subject']),
// 靠mapGetters函数来实现上面的代码(对象和数组写法)
...mapGetters({bigSum: 'bigSum'}),
...mapGetters(['bigSum'])
},
5.2.3 mapActions 与 mapMutations
3.mapActions:帮助我们生成与actions
对话的方法,即:包含$store.dispatch(xxx)
的函数
4.mapMutations:帮助我们生成与mutations
对话的方法,即:包含$store.commit(xxx)
的函数
methods: {
//使用mapMutations实现程序员费老大劲写的代码联系mutations
...mapMutations({ add: 'JIA', subtract: 'JIAN' }),
//如果键值名字一样,可以用数组简写,记得页面也要同步
...mapMutations(['JIA', 'JIAN']),
//使用mapActions实现程序员费老大劲写的代码联系actions
...mapActions({ oddAdd: 'oddAdd', waitAdd: 'waitAdd' }),
...mapActions(['oddAdd', 'waitAdd']),
},
备注:
mapActions
与mapMutations
使用时,若需要传递参数:在模板中绑定事件时传递好参数,否则参数是事件对象