您好,欢迎访问一九零五行业门户网

vue的辅助函数有哪些

vue的辅助函数有:1、mapstate,将全局状态管理的state值映射到组件的计算属性;2、mapgetters,将全局状态管理的getters值映射到组件的计算属性;3、mapactions;4、mapmutations。
本教程操作环境:windows7系统、vue2.9.6版,dell g3电脑。
1.vue的辅助函数mapstate、mapgetters、mapactions、mapmutations
mapstate 将全局状态管理的state值映射到组件的计算属性
mapgetters 将全局状态管理的getters值映射到组件的计算属性
mapmutation 将mutation的值映射到方法里
mapactions 将actions里的值映射到方法里
2.mapstate 辅助函数mapstate是什么?官方的解释是:
当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapstate 辅助函数帮助我们生成计算属性,让你少按几次键
当初在看到这个解释的时候可能觉得非常空洞,难以理解。生成计算属性是什么?少按几次键???
mapstate是state的语法糖,什么是语法糖?我对语法糖的理解就是,我明明已经对一种操作很熟练了,并且这种操作也不存在什么问题,为什么要用所谓的更好,更好的操作?,用了一段时间后,真香!
3.如何使用在使用mapstate之前,要导入这个辅助函数。
import { mapstate } from 'vuex'
使用方式
<template> <div id="example"> <button @click="decrement">-</button> {{count}} {{datacount}} <button @click="increment">+</button> <div>{{sex}}</div> <div>{{from}}</div> <div>{{mycmpted}}</div> </div></template><script>import { mapstate } from 'vuex'export default { data () { return { str: '国籍', datacount: this.$store.state.count } }, computed: mapstate({ count: 'count', // 第一种写法 sex: (state) => state.sex, // 第二种写法 from: function (state) { // 用普通函数this指向vue实例,要注意 return this.str + ':' + state.from }, // 注意下面的写法看起来和上面相同,事实上箭头函数的this指针并没有指向vue实例,因此不要滥用箭头函数 // from: (state) => this.str + ':' + state.from mycmpted: function () { // 这里不需要state,测试一下computed的原有用法 return '测试' + this.str } }), methods: { increment () { this.$store.commit('increment') }, decrement () { this.$store.commit('decrement') } }}</script>
computed可以接收mapstate函数的返回值,你可以用代码中的三种方式去接收store中的值,具体可以看注释。
如果我在后面想使用mapstate怎么办?其实很简单
//之前的computedcomputed:{ fn1(){ return ...}, fn2(){ return ...}, fn3(){ return ...} ........}//引入mapstate辅助函数之后 computed:mapstate({ //先复制粘贴 fn1(){ return ...}, fn2(){ return ...}, fn3(){ return ...} ...... //再维护vuex count:'count' })
4.对象展开运算符…mapstate并不是mapstate的扩展,而是…对象展开符的扩展 。
//之前的computedcomputed:{ fn1(){ return ...}, fn2(){ return ...}, fn3(){ return ...} ........}//引入mapstate辅助函数之后 computed:{ //原来的继续保留 fn1(){ return ...}, fn2(){ return ...}, fn3(){ return ...} ...... //再维护vuex ...mapstate({ //这里的...不是省略号了,是对象扩展符 count:'count' })
mapstate、mapgetters、mapactions、mapmutations的使用方法大同小异。。。
【相关推荐:《vue.js教程》】
以上就是vue的辅助函数有哪些的详细内容。
其它类似信息

推荐信息