• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

vuex mapState mapGetters用法以和多个module模块下用法

武飞扬头像
矢心%
帮助1


前言

在vuex,当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余,例如

computed: {
  count() {
    return this.$store.state.count
  },
  name() {
    return this.$store.state.name
  },
  age() {
    return this.$store.getter.age
  },
  userInfo() {
    return this.$store.getter.userInfo
  }
}

为了解决这个问题,我们可以使用 mapState和mapGetters 辅助函数帮助我们生成计算属性,让你少按几次键


一、mapState

1、对象写法

// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'

export default {
  computed: mapState({
  
    // 传函数参数
    count: state => state.count, // 箭头函数可使代码更简练 映射为this.count
    userCount: state => state => state.user.count, // 模块化写法 箭头函数可使代码更简练 映射为this.userCount
    
    // 传字符串参数
    userName: 'name', // name等同于state => state.name,不支持模块化写法 映射为this.userName
    
    // 需要使用this局部状态,使用常规函数写法
    age(state) { // 映射为this.age
      return state.age   this.age // 可与局部状态组合
    }
  })
}
学新通

2、字符串数组写法

除此之外,还有更简洁的写法
当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组,类似于对象的key和value键名相同时{ name: name } =》{ name }

computed: mapState([
  'count', // 映射 this.count 为 store.state.count
  'name' // 映射 this.name为 store.state.name
])

此外如果是用到了module模块化,除了将对象作为参数传递之外,namespaced mapState还可以使用两个参数:namespace和表示模块成员的对象名称数组,像这样

computed: mapState('user', ['count', 'name']) // user 模块名称

3、使用展开运算符

mapState 函数返回的是一个对象,这样就造成无法与当前局部组件计算属性混合使用
以前我们需要使用一个工具函数将多个对象合并为一个,以使我们可以将最终对象传给 computed 属性。
自从有了展开运算符后,可以极大地简化写法

computed: {
  ...mapState([
    'count', // 映射 this.count 为 store.state.count
    'name' // 映射 this.name为 store.state.name
  ]),
  // 局部组件计算属性
  localComputed () {},
}

二、mapGetters

mapGetters辅助函数写法相同

computed: {
  ...mapGetters([
    'count', // 映射 this.count 为 store.getters.count
    'name' // 映射 this.name为 store.getters.name
  ]),
  // 局部组件计算属性
  localComputed () {},
}

模块化写法

...mapGetters('user', ['count', 'name']) // user 模块名称

三、mapActions、mapMutations

mapActions、mapMutations用法相同,他们的作用都是把actions、mutations里的方法映射到局部组件调用

例如:

以前的调用actions:

this.$store.dispatch("test", "value")
this.$store.dispatch("user/test", "value") // user模块化, 第二个参数为传参

使用辅助函数后调用

...mapActions([
    "test",
])

this.test('value')

总结

总结以上,推荐使用展开运算符 字符串数组传参的方式使用,可以极大简化代码,更优雅,不冗余

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhghckgg
系列文章
更多 icon
同类精品
更多 icon
继续加载