Module 介绍
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时, store 对象就有可能变得相当臃肿。
为了解决以上问题, Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割。
Module 构建
在 store 目录下新建 modules 目录,并在下面新建 moduleA.js 和 moduleB.js 文件来存放 vuex 的 modules 模块。
|—— components # 组件文件夹
|—— myButton
|—— myButton.vue # myButton 组件
|—— pages
|—— index
|—— index.vue # index 页面
|—— static
|—— store
|—— index.js # 我们组装模块并导出 store 的地方
|—— modules # 模块文件夹
|—— modulesA.js # 模块moduleA
|—— modulesB.js # 模块moduleB
|—— App.vue
|—— main.js
|—— mainfest.json
|—— pages.json
|—— uni.scss
在 main.js 文件中引入 store
/* 文件路径:main.js */
import Vue from 'vue'
import App from './App'
import store from './store'
Vue.prototype.$store = store
// 把 store 对象提供给 store 选项,这可以把 store 的实例注入所有的子组件
const app = new Vue({
store,
...App
})
app.$mount()
在项目根目录下,新建 store 目录,并在下面新建 index.js 文件,作为模块入口,引入各子模块
/* 文件路径:store/index.js */
import Vue from 'vue'
import Vuex from 'vuex'
import moduleA from '@/store/modules/moduleA'
import moduleB from '@/store/modules/moduleB'
Vue.use(vuex)
export default new Vuex.Store({
modules: {
moduleA, moduleB
}
})
子模块 moduleA 页面内容
/* 子模块 moduleA 文件路径:store/modules/moduleA.js */
export default {
state: {
text: "我是 moduleA 模块下的 state.text 的值"
},
getters: {
},
mutations: {
},
actions: {
}
}
子模块 moduleB 页面内容
/* 子模块 moduleB 文件路径:store/modules/moduleB.js */
export default {
state: {
timestamp: 1608820295 // 初始时间戳
},
getters: {
timeString(state) {
// 时间戳转换后的时间
var date = new Date(state.timestamp);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var trMon = mon < 10 ? '0' + month : month;
var rtDay = day < 10 ? '0' + day : day;
return year + '-' + trMon + '-' + trDay + ' ' + hours + ':' + minutes + ':' + seconds;
}
},
mutatuions: {
updateTime(state) { // 更新当前时间戳
state.timestamp = Date.now()
}
},
actions: {
}
}
在页面中引用组件 myButton ,并通过 mapState 读取 state 的初始数据
<!-- 页面路径:pages/index/index.vue -->
<template>
<view class="content">
<view>{{text}}</view>
<view>时间戳:{{timestamp}}</view>
<view>当前时间:{{timeString}}</view>
<myButton></myButton>
</view>
</template>
<script>
import {mapState, mapGetters} from 'vuex'
export default {
computed: {
...mapState({
text: state => state.moduleA.text,
timestamp: state => state.moduleB.timastamp
}),
...mapGetters([
'timeString'
])
}
}
</script>
在组件 myButton 中,通过 mutations 操作刷新当前时间。
<!-- 组件路径:components/myButton/myButton.vue -->
<template>
<view>
<button type="default" @click="updateTime">刷新当前时间</button>
</view>
</template>
<script>
import {mapMutations} from 'vuex'
export default {
data() {
return {}
},
methods: {
...mapMutations(['updateTime'])
}
}
</script>
vue 是单向数据流,子组件不能直接修改父组件的数据,而通过 vuex 状态管理实现:
把组件的公共状态抽取出来,以一个全局单例模式管理。在这种模式下,我们的组件树构成了一个巨大的“视图”,不管在树的哪个位置,任何组件都能获取状态或者触发行为。
🔥BuildAdmin是一个永久免费开源,无需授权即可商业使用,且使用了流行技术栈快速创建商业级后台管理系统。