当前位置: 首页 > 科技观察

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

时间:2023-03-19 23:45:31 科技观察

程序员都知道的vuex的冷门tricks超级好用超级好用,尤其是当项目很大的时候,代码会看起来很简洁,容易维护,但是当项目很大的时候,vuex的嵌套公共数据会越来越深,组件中使用的组件有时会像下图这样。我必须点击并点击才能获取最里面的数据。项目做大需要很长时间...image.png在我不断的尝试中,我成功地发现vuex其实有一个辅助功能图可以解决这个问题。把自己总结的语法分享给大家~希望对大家有所帮助。辅助函数map的作用:简化state、getters、mutations、actions的使用###MapState使用步骤//1.导入辅助函数mapState,它是vuex中定义的实用函数。//es6importondemandimport{mapState}from'vuex'import{mapState}from'vuex'computed:{//解释一:...object是将对象展开合并到computed中//解释二:mapState是一个函数//['dataitem1','dataitem2']...mapState(['xxx']),...mapState({'newname':'xxx'})}CopyCode####使用脚本:this.xxx模板:{{xxx}}复制代码说明:image.png原理mapState是一个辅助函数,将vuex中的数据投射到组件中;computed:{...mapState()}这里...是对象的展开算子,是对象整体的合并。如果vuex中的数据和这个组件中的数据重名怎么办?辅助函数mapState重命名数据...mapState({'newname':'xxx'})##Vuex-map函数使用总结图.png直接使用全局状态:this.$store.state.xxx;maphelperfunction:computed:{//省略其他计算属性...mapState(['xxx']),...mapState({'newName':'xxx'})}复制代码,如果是怎么办分成模块?如何在模块中使用状态?图片image.png直接使用:this.$store.state.modulename.xxx;map辅助函数:computed:{...mapState('modulename',['xxx']),...mapState('modulename',{'newname':'xxx'})}复制代码,直接使用全局getters:this.$store.getters.xxxmaphelperfunction:computed:{...mapGetters(['xxx']),...mapGetters({'newname':'xxx'})}复制代码在模块中使用getters直接使用:this.$store.getters.modulename.xxxmap辅助函数:computed:{...mapGetters('modulename',['xxx']),...mapGetters('modulename',{'newName':'xxx'})}复制代码使用全局突变直接使用:this.$store.commit('mutationname',parameter)maphelperfunction:methods:{...mapMutations(['mutationname']),...mapMutations({'newname':'mutationname'})}复制代码使用模块中的突变(命名空间:true)直接使用:this.$store.commit('modulename/mutationname',parameters)maphelperfunction:methods:{...mapMutations('modulename',['xxx']),...mapMutations('模块Name',{'newname':'xxx'})}复制代码使用全局动作直接使用:this.$store.dispatch('actionname',parameter)maphelperfunction:methods:{...mapActions(['actionsname']),...mapActions({'newname':'actionsname'})}复制代码在模块中使用actions(namespaced:true)直接使用:this.$store.dispatch('modulename/actionname',parameter)maphelperfunction:methods:{...mapActions('模块名称',['xxx']),...mapActions('模块名称',{'新名称':'xxx'})}复制代码如果namespaced为true,则需要添加额外的模块名称如果namespaced为false,则不需要添加额外的模块名称Summary