zoukankan      html  css  js  c++  java
  • vuex中mapState、mapMutations、mapAction的理解

    当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性。

     1 // 在单独构建的版本中辅助函数为 Vuex.mapState
     2 import { mapState } from 'vuex'
     3  
     4 export default {
     5   // ...
     6   computed: mapState({
     7     // 箭头函数可使代码更简练,es6的箭头函数,传入参数是state,返回值是state.count。然后把返回值映射给count,此时调用this.count就是store里的count值
     8     count: state => state.count,
     9  
    10     // 传字符串参数 'count' 等同于 `state => state.count`
    11     countAlias: 'count',
    12  
    13     // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    14     countPlusLocalState (state) {
    15       return state.count + this.localCount
    16     }
    17   })
    18 }

    mapState 函数返回的是一个对象。我们如何将它与局部计算属性混合使用呢?通常,我们需要使用一个工具函数将多个对象合并为一个,以使我们可以将最终对象传给 computed 属性。但是自从有了对象展开运算符(现处于 ECMASCript 提案 stage-4 阶段),我们可以极大地简化写法:
     

    1. 1 computed: {
      2   localComputed () { /* ... */ },
      3   // 使用对象展开运算符将此对象混入到外部对象中
      4   ...mapState({
      5     // ...
      6   })
      7 }
      对象扩展运算符:
    1. 1 <span style="font-size:14px;">let z = { a: 3, b: 4 };  
      2 let n = { ...z };  
      3 n // { a: 3, b: 4 }</span> 
    2.  

    当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
     

    1. 1 computed: mapState([
      2   // 映射 this.count 为 store.state.count
      3   'count'
      4 ])
    2.  

    mapMutations和mapActions:
     

    mapMutations/mapActions只是把mutation/action函数绑定到methods里面,调里面的方法时正常传参数。

    注意:映射都是映射到当前对象,使用时需要用this来调用。

    例如:

    1 methods:{
    2     ...mapMutations(['login'])
    3 }
    4 
    5 
    6 
    7 下面使用this.login(data);

  • 相关阅读:
    刷题238. Product of Array Except Self
    刷题236. Lowest Common Ancestor of a Binary Tree
    刷题208. Implement Trie (Prefix Tree)
    A1070
    A1048
    A1050
    A1041
    A1092
    A1084
    n进制转十进制
  • 原文地址:https://www.cnblogs.com/ajaxlu/p/11974816.html
Copyright © 2011-2022 走看看