1.前言
vuex
作为vue
中最流行的状态管理工具,在vue3
版本使用的时候也是有些注意事项的 总结如下
2. store
只是讲解和
v2
不同的地方,store
文件v3
一样
这里这个store
就不拆分了,看起来费劲
import { createStore } from 'vuex'
export default createStore({
state: {
num: 1,
carList: [
{ carName: "毛豆Y", price: 27, range: 568 },
{ carName: "极氪001", price: 28, range: 620 },
{ carName: "零跑C11", price: 19, range: 520 },
{ carName: "比亚迪汉", price: 23, range: 610 }
],
userInfo: {}
},
getters: {
doubleNum(state) {
return Math.pow(state.num, 2)
},
userVipList(state) {
return state.carList.filter(v => v.range > 600)
}
},
mutations: {
increase(state, { payload = 10 }) {
state.num += payload
},
setCarList(state, { payload }) {
return state.carList = payload
},
delList(state, index) {
state.carList.splice(index, 1);
},
updateUserInfo(state, obj) {
state.userInfo = obj
console.log("存储成功",state)
},
},
actions: {
getActionList(context) {
// 模拟异步请求
setTimeout(() => {
context.commit("setCarList", { payload: [{ carName: "极氪001", price: 28, range: 620 },] })
}, 1000)
},
delCarList(context,index) {
setTimeout(() => {
//触发mutations中的方法 变更状态
context.commit("delList", index);
}, 1000)
}
},
modules: {
}
})
3.不使用辅助函数
3.1.1 直接访问 store state
直接使用 和
v2
用法一样
vuex数据-state:{{$store.state.num}}
- {{item.carName}}
3.1.2 计算属性 同名
computed:mapState(["num"]),
这种写法 就只能使用
num
的名字
3.1.3 计算属性 computed 别名-1
computed:{
num(){
return this.$store.state.num
}
},
这种方式 新的计算属性的名字也可以 换个名字不叫
num
3.1.4 计算属性 computed 别名-2
computed:mapState({
otherNum:state=>state.num,
}),
3.1.5 计算属性 computed 别名-3
computed:mapState({
n:"num"
}),
3.2 访问 store getter
vuex-getters:{{$store.getters.doubleNum}}
3.3 mutation
vuex数据修改-mutation:
直接使用了
setup
3.4 action
vuex数据修改-action:
let changeCar = ()=>{
store.dispatch("getActionList")
}
4. 辅助函数
4.1 直接上 模板
vuex-辅助函数
vuex数据-state:{{ num }}
vuex数据修改-mutation:
vuex数据修改-action:
-
{{ item.carName }}
vuex-getters:{{ doubleNum }}
4.2 逻辑
5. 实际使用注意数据响应式
Object.assign(targetObj,obj)
赋值一个对象到目标对象
返回修改后的目标对象