mapState与mapGetters语法糖

mapState与mapGetters语法糖vuex中的mapState,mapGetters属于辅助函数,其实就是vuex的一个语法糖,使代码更简洁更优雅。<script>import{mapState,mapGetters}from”vuex”exportdefault{computed:{ //原先templateInfo(){ returnthis.$store.state.templateInfo},//现在

大家好,又见面了,我是你们的朋友全栈君。

vuex中的 mapState,mapGetters 属于辅助函数,其实就是vuex的一个语法糖,使代码更简洁更优雅。

import { 
    mapState, mapGetters } from "vuex"
export default { 
   
    computed: { 
   
    	//原先state中的数据
        templateInfo(){ 
   
        	return this.$store.state.templateInfo
        },
        //现在
        ...mapState([
            "templateInfo",   
        ]),
        //原先getters中的数据
        isPreview(){ 
   
        	return this.$store.getters.isPreview
        },
        //现在
        ...mapGetters([
            'isPreview'
        ])
    },
    created(){ 
   
     	//使用时
     	this.templateInfo,
     	this.isPreview
	}
}

mapState与mapGetters只能在computed中使用,与正常的computed中的函数一起使用时需要用扩展运算符,然后在mapState或mapGetters函数的数组中放入对应的state或getters中的名称。

1.若要使用某个模块中的state,则第一个参数是模块名称

...mapState("moduleA", { 
   
      test1: state => state.test1,
      test2: "test2"
 }),

2.若要使用多个模块中的state,以上方法有点太累赘,则用以下方法

...mapState({ 
   
      currentType: state => state.app.currentType,
      userId: state => state.user.userId,
}),

以上两种方法对getters同样有效。

3.通过state中的值再动态计算出getters中的值

const getters = { 
   
  alarmName: state => { 
   
    return (row) => state.app.alarmTypes.find(item => item.alarmType == row.alarmType)
  },
},
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/145174.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号