1

程序员都知道的vuex的冷门小技巧,超好用

 1 year ago
source link: https://www.fly63.com/article/detial/11625
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

当访问某个数据项嵌套太深了,优化一下访问的方式

我相信每一个程序员都会使用vuex吧,首先我承认vuex真的超好用,尤其是在项目特别大的时候,代码会看起来非常的简洁,也方便维护,但是项目大了,vuex的公共数据的嵌套也会越来越深,在组件中使用的时候就会像下面这张图一样,我要一直点啊点,才能拿到最里面的数据,项目大了点都要点老半天......

6296cbddb0b7c.jpg

在我的不断尝试中,成功的发现了,vuex其实有一个辅助函数map可以解决这个问题,下面就把我总结到的语法分享给大家啦~希望可以帮到你

辅助函数map作用:简化使用state, getters, mutatioins, actions

mapState的使用步骤

// 1. 导入辅助函数mapState,它是在vuex中定义的一个工具函数。
//  es6 按需导入 import { mapState } from 'vuex' 
import { mapState } from 'vuex'

computed: {
   // 说明1: ...对象 是把对象展开,合并到computed
   // 说明2: mapState是一个函数 
   //  ['数据项1', '数据项2']
   ...mapState(['xxx']),
   ...mapState({'新名字': 'xxx'})
}
script:   this.xxx
模板:     {{xxx}}
6296cbe655a69.jpg

mapState是辅助函数,将vuex中的数据投射到组件内部;

computed:{ ...mapState() } 这里的...是对象的展开运算符,整体来看是对象的合并。

如果vuex中的数据与本组件内的数据名相同,怎么办呢?

辅助函数mapState对数据重命名

...mapState({'新名字': 'xxx'})

## Vuex-map函数用法汇总

6296cbeaebfaf.jpg

使用全局state

直接使用: this.$store.state.xxx;

map辅助函数:

computed: { 
  // 省略其他计算属性
  ...mapState(['xxx']), 
  ...mapState({'新名字': 'xxx'})
}

那如果是分模块化呢?如何使用modules中的state?

图示

6296cbf0f3c8c.jpg

直接使用: this.$store.state.模块名.xxx;

map辅助函数:

computed: { 
  ...mapState('模块名', ['xxx']), 
  ...mapState('模块名', {'新名字': 'xxx'})
}

使用全局getters

直接使用:this.$store.getters.xxx

map辅助函数:

computed: { 
  ...mapGetters(['xxx']), 
  ...mapGetters({'新名字': 'xxx'})
}

使用modules中的getters

直接使用: this.$store.getters.模块名.xxx

map辅助函数:

computed: { 
  ...mapGetters('模块名', ['xxx']), 
  ...mapGetters('模块名',{'新名字': 'xxx'})
}

使用全局mutations

直接使用:this.$store.commit('mutation名', 参数)

map辅助函数:

methods: { 
  ...mapMutations(['mutation名']), 
  ...mapMutations({'新名字': 'mutation名'})
}

使用modules中的mutations(namespaced:true)

直接使用: this.$store.commit('模块名/mutation名', 参数)

map辅助函数:

methods: { 
  ...mapMutations('模块名', ['xxx']), 
  ...mapMutations('模块名',{'新名字': 'xxx'})
}

使用全局actions

直接使用:this.$store.dispatch('action名', 参数)

map辅助函数:

methods: { 
  ...mapActions(['actions名']), 
  ...mapActions({'新名字': 'actions名'})
}

使用modules中的actions(namespaced:true)

直接使用: this.$store.dispatch('模块名/action名', 参数)

map辅助函数:

methods: { 
  ...mapActions('模块名', ['xxx']), 
  ...mapActions('模块名',{'新名字': 'xxx'})
}

如果namespaced为true,则需要额外去补充模块名

如果namespaced为false,则不需要额外补充模块名

总结

6296cbf82a424.jpg
作者:你睡醒了吗
链接:https://juejin.cn/post/7097568476155838494

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK