木灵鱼儿
阅读:7337
vuex namespaced 命名空间
我们有时候在使用vuex模块的时候,在其中加了一个键值对为:namespaced : true
export default {
namespaced: true,
state {
zoom: 15
},
getters:{},
mutations:{},
actions:{},
}
namespaced为true
的作用是告诉vuex,该模块所有的state 、getters、mutations、actions里面的东西调用时都需要加上命名空间,这个命名空间就是该模块被improt时命名的名字。
假设这个模块的名字为map.js
我们引入
import map from './map'
export default new Vuex.Store({
modules: {
map
}
})
map就是他的命名空间
调用的时候
this.$store.state.map.zoom;
如果是方法,getters,mutations,actions,他的调用略有不同
getters:{
zoom(state){
return state.zoom;
}
}
调用:
this.$store.getters['map/zoom'];
如果使用辅助函数...mapGetters()
...mapGetters({
zoom : 'map/zoom'
})
或者指定一个命名空间
...mapGetters('map',['zoom'])
如果你的模块嵌套了多个的话,也可以指定
...mapGetters('map/config/mapcontent',['zoom'])
这样获取的是map模块里面的config模块里面的mapcontent模块中的_zoom_
另一种方式是使用createNamespacedHelpers
方法
import { createNamespacedHelpers } from "vuex";
const {mapGetters} = createNamespacedHelpers('map');
export default {
computed: mapGetters(['zoom']);
}
访问全局元素
我们可以在getter中访问根状态和根getter
getters :{
zoom: (state,getters,rootState,rootGetters)=>{
}
}
- state为当前模块的state
- getters为当前模块的getters
- rootState为根元素state
- rootGetters为根元素getters
通过rootState我们可以访问所有的存储在state中的内容
通过rootGetters可以访问所有的getters方法
而在action中,略有不同
actions:{
zoom: ({dispatch,commit,getters,rootGetters})=>{
commit("zoom",2,{root:true})
}
}
除了基本的引入对应的dispatch,commit这些,还有rootGetters这些根元素
通过根元素可以访问可以理解,那么{root:true}
这个第三个参数什么意思?
它表示触发的是根元素的commit中的zoom方法
版权申明
本文系作者 @木灵鱼儿 原创发布在木灵鱼儿 - 有梦就能远航站点。未经许可,禁止转载。
相关推荐
第四章 对象的创建
命名空间在ESM模块化还未出来之前,用于减少全局变量名污染的一种做法就是使用命名空间,其做法也非常简单,就是创建一个全局的变量,然后将内容都赋值给这个变量,从而减少对全局变量的使用。//创建命名空间 var MYAPP = {}; //构造函数 MYAPP.Parent = function(){}; MYAPP.Child = function(){}; // 一个变量 MYAPP.some_var =1; // 一个对象容器 MYAPP.modules ={}; // 嵌套的对象 MYAPP.modules.module1 ={}; MYAPP.modules.module1...