zoukankan      html  css  js  c++  java
  • vuex入门(2)-辅助函数mapState和mapMutations

    上一篇文章中,我们介绍了vuex的基本概念和使用方法
    当需要共享的数据比较简单且都是同步操作时,组件可以跳过Action,直接用 commit 方法调用Mutations
    同时我们也可以借助两个辅助函数简化我们的代码
    mapState和mapMutations可以接收数组或者对象作为参数
    将store中的状态映射到当前组件

    一、mapState

    获取store中city变量的一般写法为:

    {{this.$store.state.city}}
    

    我们可以在组件中引入mapState,将state映射到当前组件,简化代码:

    <script>
    import { mapState } from 'vuex'
    export default {
      name: ' ',
      computed: {
        ...mapState({
          // 将state中的city映射到当前组件中的currentCity
          currentCity: 'city'
        })
      }
    }
    </script>
    

    在这种情况下,获取city变量就可以这么写:

    {{this.currentCity}}
    

    二、mapMutations

    组件通过commit方法调用mutation的一般写法:

    {{this.$store.commit('changeCity', city)}}
    

    同理,我们可以引入mapMutations,简化代码:

    <script>
    import { mapMutations } from 'vuex'
    export default {
      name: ' ',
      methods: {
        handleCityClick (city) {
          this.changeCity(city)
        },
        // 将 state中的 changeCity映射到当前组件
        ...mapMutations(['changeCity'])
      }
    }
    </script>
    
  • 相关阅读:
    c#格林治时间实现
    K3WISE常用表
    读取单元格数据
    水晶报表使用方法
    vs2010下使用sqlite
    C#执行EXE程序
    SQLLITE HELPER
    SQL LITE安装
    C#多线程
    VS2012 快捷键
  • 原文地址:https://www.cnblogs.com/baebae996/p/13366595.html
Copyright © 2011-2022 走看看