美文网首页
vuex的辅助函数

vuex的辅助函数

作者: 懒懒猫 | 来源:发表于2022-08-28 11:08 被阅读0次

    子组件

    一、什么时候需要使用辅助函数

    当一个组件需要获取多个状态的时候,使用方式会有些重复和冗余。为了解决这个问题,我们可以使用辅助函数来简化使用方式,让我们少按几次键

    二、按需引入四个辅助函数

            import { mapState,mapGetters,mapActions,mapMutations } from "vuex";
    

    三、辅助函数的位置

            mapState,mapGetters在computed中使用,而且在所有自定义计算属性的上方
            mapActions,mapMutations在methods中使用,而且在所有方法的上方
    

    四、示例:

      export default {
                            name: "index",
                              computed: {
                                ...mapState(['msg','goodsList' ]),
                                ...mapGetters([ 'goodScore']),
                                //自定义计算属性
                                getDate(){
                                    return Date.now()
                                }
                            },
                            methods: {
                                ...mapActions([ 'getGoodsList']),
                                ...mapMutations(['changeMsg' ]),
                                change(){
                                    this.changeMsg('1')
                                }
                            }
    }
    

    五、使用辅助函数后,再访问store数据,直接调用实例自身的变量即可

            以前:  this.$store.state.msg
            现在:  this.msg
    
            以前:  this.$store.commit("方法名")
            现在:  this.方法名()
    

    相关文章

      网友评论

          本文标题:vuex的辅助函数

          本文链接:https://www.haomeiwen.com/subject/lgbtkltx.html