您现在的位置是:网站首页> 编程资料编程资料

vuex中...mapstate和...mapgetters的区别及说明_vue.js_

2023-05-24 963人已围观

简介 vuex中...mapstate和...mapgetters的区别及说明_vue.js_

...mapstate和...mapgetters的区别

…mapstate

当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。

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

官方文档如上

因为state相当于data,getters相当于计算属性,个人理解如果只需要拿到state中一个值,就没必要在getters中作为计算属性出现。

…mapGetters

辅助函数仅仅是将 store 中的 getter 映射到局部计算属性

如果你想将一个 getter 属性另取一个名字,使用对象形式:

...mapGetters({   // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`   doneCount: 'doneTodosCount' })

官方文档如上

相当于计算属性,等于把vuex中的计算属性映射到了当前组件中

vuex mapState mapGetters用法及多个module下用法

在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')

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

这些仅为个人经验,希望能给大家一个参考,也希望大家多多支持。 

-六神源码网