vuex Modules 设置 使用
vuex Modules 的简绍 与 使用由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:vuex的基本使用 建议先了解这
·
vuex Modules 的简绍 与 使用
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:
vuex的基本使用 建议先了解这个 再看下文 https://blog.csdn.net/dwp_wz/article/details/107976732
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
设置
大概意思就是, 我们把 vuex 分成一个个 模块了。
不分也可以, 但是 体积大了会比较臃肿。
而分成各个模块也简单
就是创建 一个个vuex格式的对象, 对象设置就和普通vuex设置一样使用
最后在将这些对象 放入
const store = new Vuex.Store({
modules: {
a: moduleA, // 就是这一步
b: moduleB
}
})
页面使用
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')
export default {
computed: {
// 在 `some/nested/module` 中查找
...mapState({
a: state => state.a.a, // state.a模块.a的state中的值a
b: state => state.b.b
})
},
methods: {
// 在 `some/nested/module` 中查找
...mapActions([
'foo', // 方法到没什么
'bar'
])
}
}
或者:
computed: {
...mapState({
a: state => state.some.nested.module.a,
b: state => state.some.nested.module.b
})
},
methods: {
...mapActions([
'some/nested/module/foo', // -> this['some/nested/module/foo']()
'some/nested/module/bar' // -> this['some/nested/module/bar']()
])
}
例子:
最后
vuex 官网 https://vuex.vuejs.org/zh/guide/modules.html
vuex的基本使用 https://blog.csdn.net/dwp_wz/article/details/107976732
最后的最后 点赞 收藏 不吃亏
更多推荐
已为社区贡献17条内容
所有评论(0)