标签:状态 vue getters Module 用法 state store
系列导航
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>
标签:状态,vue,getters,Module,用法,state,store 来源: https://www.cnblogs.com/yclh/p/15855403.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。