一、搭建环境
1.安装vuex
安装:npm i vuex@3
注意Vue2一定要安装vuex3,如果是vue3可以直接npm i vuex
安装的是vuex4
2.创建store文件
1.创建文件:src/store/index.js
在store文件中引入vuex,若在mian.js文件中引入会报错,因为import语句变量提升,在store中找不到要使用的vuex,因此会报错
// 该文件用于创建vuex 中最为核心的store
// 引入
import Vuex from "vuex"
import Vue from "vue"
Vue.use(Vuex)
// 准备Actions,用于响应组件,我理解为中转站,告诉函数要执行什么命令
const actions={
jia1(context,value){
context.commit("jia2",value)
},
jian1(context,value){
context.commit("jian2",value)
},
jishu1(context,value){
if(context.state.sum%2!==0){
context.commit("jishu2",value)
}
},
wait1(context,value){
setTimeout(() => {
context.commit("wait2",value)
},1000)
}
}
// 准备mutations,用于操作数据(state
const mutations={
jia2(state,value){
state.sum=state.sum+value
},
jian2(state,value){
state.sum=state.sum-value
},
jishu2(state,value){
state.sum=state.sum+value
},
wait2(state,value){
console.log(this)
state.sum=state.sum+value
}
}
// 准备state 存储数据
const state={
sum:0
}
// 创建store
export default new Vuex.Store({
actions,
mutations,
state
})
// 有引用提升,在main.js中先把store提升了,但是在这里面创建实例的时候并没有在main.js中使用,触发什么就执行什么,因此函数名要一致,这里和事件总线,消息订阅与发布=的触发机制类似
// 暴露store
2.在mian.js文件中暴露
import store from "./store/index.js"
3.在组件中的使用
1.调用仓库中的数据时,$store.state.xxx
当前和为{{$store.state.sum}}
jia(){
this.$store.dispatch("jia1",this.n)
},
2.在组件中的回调就可以用dispatch
发给actions
(点菜),注意如果没有业务逻辑,直接commit
可以跳过actions
直接给mutations
jia1(context,value){
context.commit("jia2",value)
3.在actions
中使用jia
这个函数来接(处理顾客需求),并且使用commit
发给mutations
(需求告诉厨师)。这里jia
函数会接到两个参数,第一个参数是浓缩版的$store
,方便你在这里调用commit
把东西给mutations
,第二个参数是组件那边传过来的数据。
JIA(state, value) {
//第一个参数是state对象,第二个参数是传过来的数据
console.log('mutations中的JIA被调用了 ', state, value);
state.sum += value;
}
在mutations
中使用JIA
这个函数来接(做菜),一般都写成actions
对应函数的大写,意思是mutations
更nb。也是接两个参数,第一个参数是state对象,第二个参数是传过来的数据,就是仓库中的属性,将数据添加到仓库身上。
4.配置getters
getters用于数据的加工,将数据处理成好写的方式
展示数据,1.用计算属性
where1(){
return this.$store.state.where
},
2.用mapState
...mapState({xxx: (state) => {return state.xxx })
3.用mapGetters
...mapGetters(["xxx","yyy"])