zoukankan      html  css  js  c++  java
  • Vuex的辅助函数mapState, mapActions, mapMutations用法

    直接代码解说

    store/index.js (简单书写)

    export default new Vuex.Store({
        state: {
            add: 10
        },
        mutations: {
            change(state,a) {
                state.add += a
            }
        }
    })
    

    在一般的情况下,我们想要拿到add这个值,就需要使用this. $store.state.add来获取,但是这样的代码片段太长了

    前提:

    import { mapState, mapActions, mapMutations} from 'vuex'
    //使用都分为两种方式:对象和数组,但是自我推荐,使用对象的形式,更加有利于理解
    

    mapState的使用

    computed: {
        //第一种方式
        ...mapState({
            add: state => state.add
        })
        //第二种方式,以数组的方式
        ...mapState(['add'])  //必须要加冒号
    }
    
    

    mapMutations的使用

    //调用Mutations 需要时使用 this.$store.commit('change', 1) 这样的
    
    //第一种方式,使用数组的形式
    ...mapMutations(['change']), // 会将 this.change 映射成 this.$store.commit('change') 
    //第二种方式,使用对象的形式
    ...mapMutations({
        'change': 'change'  //前面这个属性可以随便写,但是后面的属性值要与mutations中对应起来
     })
    //传参: 跟普通的方法一样,直接把参数写在调用函数的括号里,就OK了。
    

    mapActions的使用(对异步函数的操作)

    //调用Actions 需要时使用 this.$store.dispatch('asyn', 1) 这样的
    
    //第一种方式,使用数组的形式
    ...mapActions(['asyn']), // 会将 this.asyn 映射成 this.$store.dispatch('asyn') 
    //第二种方式,使用对象的形式
    ...mapActions({
        'asyn': 'asyn'  //前面这个属性可以随便写,但是后面的属性值要与actions中对应起来
     })
    
  • 相关阅读:
    notification(浏览器通知)
    面试的信心来源于过硬的基础
    碰撞检测
    使用自定义的鼠标图标 --- cursor url
    js中json字符串转成js对象
    【php学习】字符串操作
    Car的旅行路线(codevs 1041)
    Find them, Catch them(poj 1703)
    Period(poj 1961)
    Power Strings(poj 2406)
  • 原文地址:https://www.cnblogs.com/xyf724/p/13279616.html
Copyright © 2011-2022 走看看