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#】工具类-FTP操作封装类FTPHelper
    网盘搜索网站
    在线服务
    Windows下安装NTP服务器
    vue 组件间的传值 + 路由守卫
    功能6 -- 选项卡数据缓存
    vue2.0/3.0
    vuex
    mySql笔记
    Typescript
  • 原文地址:https://www.cnblogs.com/baebae996/p/13366595.html
Copyright © 2011-2022 走看看