vue 狀態管理 五、Module用法
阿新 • • 發佈:2022-01-29
系列導航
vue 狀態管理 三、Mutations和Getters用法
Module用法
一、基本知識
1、Module是模組的意思, 為什麼在Vuex中我們要使用模組呢?
(1)Vue使用單一狀態樹,那麼也意味著很多狀態都會交給Vuex來管理.
(2)當應用變得非常複雜時,store物件就有可能變得相當臃腫.
(3)為了解決這個問題, Vuex允許我們將store分割成模組(Module), 而每個模組擁有自己的state、mutation、action、getters等
2、程式碼組織形式
二、效果
頁面中呼叫action中的方法
三、目錄結構
四、原始碼
index.js
import { createStore} from 'vuex' import moduleA from './modules/moduleA' export default createStore({ state: { counter: 0, }, mutations: { }, actions: { }, getters: { }, modules: { a: moduleA } })
moduleA.js
export default { state: { name: '張三' }, mutations: { updateName(state, payload) { state.name = payload } }, getters: { fullname(state) { return state.name + 'AAAAAA' }, fullname2(state, getters) { return getters.fullname + 'BBBBBB' }, fullname3(state, getters, rootState) { return getters.fullname2 + rootState.counter } }, actions: { aUpdateName(context,payload) { console.log(context); setTimeout(() => { context.commit('updateName', payload) }, 1000) } } }
App.vue
<template> <div > <h2>----------App內容: modules中的內容----------</h2> <h2>{{$store.state.a.name}}</h2> <button @click="updateName">修改名字</button> <h2>{{$store.getters.fullname}}</h2> <h2>{{$store.getters.fullname2}}</h2> <h2>{{$store.getters.fullname3}}</h2> <button @click="asyncUpdateName">非同步修改名字</button> </div> </template> <script> import { computed } from 'vue' import { useStore } from 'vuex' export default { components: { }, methods: { updateName() { this.$store.commit('updateName', '李四') }, asyncUpdateName() { this.$store.dispatch('aUpdateName','王五') } }, setup() { return { } } } </script>