这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战
前言
VueX 是一个专门为 Vue.js 应用设计的状态管理架构,统一管理和维护各个vue组件的可变化状态(你可以理解成 vue 组件里的某些 data )。同时Vuex给我们提供了很多比较方便的函数,方便于我们使用,这篇主要总结下几个相关的辅助函数使用
辅助函数使用
-
mapState
首先在我们组件里script里导入几个函数。
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
然后在生命周期函数computed方法里使用,下面的name,permission分别对应state里定义的2个成员
computed:{
//使用对象展开运算符将此对象混入到外部对象中
...mapState(['name','permission']) // 在组件通过this就可调用,不用再写this.$store.state
},
这里使用到了一个...扩展运算符,它允许一个表达式在某处展开。展开运算符在多个参数(用于函数调用)或多个元素(用于数组字面量)或者多个变量(用于解构赋值)的地方可以使用。
在引入了之后,在我们的组件代码里就可以像如下这样获取到对应的值了
<p>{{this.name}}</p>
-
mapGetters
同样的需要在下面定义出我们的辅助函数
computed:{
// 在组件通过this就可调用,不用再写this.$store.state
...mapState(['name','permission']), ...mapGetters(['changeName']),
},
这里其实等价于在computed里定义了一个方法,如下
changeName() {
return this.$store.getters['changeName']
},
changeName对应我们store里面的changeName方法,在当前页面即可以使用
let s=this.changeName;
console.log(s);
如此便可拿到这个返回值了
-
mapMutations
mapMutations 其实跟mapState、mapGetters 的作用是类似的,将组件中的 methods 映射为store.commit 调用
我们需要在method方法里定义如下
methods:{
...mapMutations(['changeNewName']),
goUser2(){
// this.$router.push({ name: 'user2', params: { id: '123' }})
// this.$store.dispatch("changeNewName",'love actions')
let s=this.changeName;
console.log(s);
}
},
然后可以在其他方法里调用了。
changeName() {
return this.$store.getters['changeName']
},
-
mapActions
这里也就是将组件中的 methods 映射为store.dispatch 调用。同样的在我们的methods里定义i出来。
methods:{
...mapMutations(['changeNewName']),
...mapActions(['changeNewName']),
goUser2(){
// this.$router.push({ name: 'user2', params: { id: '123' }})
// this.$store.dispatch("changeNewName",'love actions')
let s=this.changeNewName('hai');
console.log(s);
}
},
定义的mapActions等价于
changeNewName() {
return this.$store.dispatch("changeNewName")
},
那么就可以跟其他的方法一样进行调用了。
辅助函数别名定义
同时可以使用别名来定义我们的方法,等价于上面我们所定义的
...mapActions({
userChange:'changeNewName'}),
...mapMutations({ userActionChange:'changeNewName'}),
其他辅助函数同理可以使用这样的别名方式来调用,然后在组件里直接this.userChange 就可以触发对应的方法了。
总结
在我们的日常开发中,对应的使用我们的辅助函数可以减少我们很多代码量,平时注意多使用,把我们的项目代码可以写的整洁。
下一篇总结下store里module的一个用法把,用于管理我们的多个状态,区分不同的业务数据状态。