1.Vuex(一)–为什么要使用Vuex
2.Vuex(二)–Vue核心概念State
3.Vuex(三)–Vue核心概念Getter
4.Vuex(四)–Vue核心概念Mutation
5.Vuex(五)–Vue核心概念Action
6.Vuex(六)–Vue核心概念Module
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割。
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 的状态
1.store.js
const moduleA = {
state: {
moduleAList: [
{
name: 'A赣州橙子',
price: '8.8'
},
{
name: 'A新疆哈密瓜',
price: '2.0'
},
{
name: 'A山东大枣',
price: '3.2'
},
{
name: 'A阳澄湖大闸蟹',
price: '10.0'
}
]
},
// 每个模块里面都可以自己的 state, getters,mutations,actions
// getters: { ... },
// mutations: { ... },
// actions: { ... }
}
const moduleB = {
state: {
moduleBList: [
{
name: 'B赣州橙子',
price: '8.8'
},
{
name: 'B新疆哈密瓜',
price: '2.0'
},
{
name: 'B山东大枣',
price: '3.2'
},
{
name: 'B阳澄湖大闸蟹',
price: '10.0'
}
]
},
getters: {
// 商品价格减半
moduleBgoodsPriceDiscount: state => {
var moduleBgoodsPriceDiscount = state.moduleBList.map(function(item){
return {
price: item.price / 2,
name: item.name
}
})
return moduleBgoodsPriceDiscount;
}
}
}
export const store = new Vuex.Store({
state: {
goodsList: [……]
},
getters: {……},
},
mutations: {……},
},
actions: {……},
modules: {
a: moduleA,
b: moduleB
}
})
2.Page9.vue
<template>
<div>
<h2>Moduleh2>
<ul class="ul_list">
<li v-for="item in moduleA">
<p class="name">商品:{{item.name}}p>
<p class="price">价格:¥{{item.price}}p>
li>
ul>
<ul class="ul_list page2">
<li v-for="item in moduleB">
<p class="name">商品:{{item.name}}p>
<p class="price">价格:¥{{item.price}}p>
li>
ul>
div>
template>
<script>
export default {
data() {
return {
}
},
computed: {
// 调用模块A中的状态
moduleA() {
return this.$store.state.a.moduleAList;
},
// 调用模块B中的getters
moduleB() {
return this.$store.getters.moduleBgoodsPriceDiscount;
}
}
}
script>
模块内部的mutations
和actions
这里就不再写了。
关于Module的内容还有很多,可以看官方文档。
请点击我!