vue3.x中vuex的modules模块化
dearweb
发布:2021-08-15 12:23:42阅读:
由于使用的是单一状态树,应用的所有状态会集中到一个比较大的对象,当应用复杂的时候,store对象就有可能变得比较臃肿,vuex为了解决上面的问题,所以采用了modules模块,将store进行分割,每个模块拥有自己的state,mutation,action和getter以及子模块也是可以自上而下进行分割的。
定义子模块
新建一个子模块命名为userStore
let userStore = {
state(){
return {
count:1,
list:'wuhan',
todos:[
{id:1,tetx:'一条河',done:true},
{id:2,tetx:'一条大河',done:false},
]
}
},
mutations:{
increment(state){
state.count++
},
setCount(state,num){
state.count = num
}
},
getters:{
doneTodos:state=>{
return state.todos.filter(todo=>todo.done)
}
},
actions:{
// 主要用于执行异步操作和mutations里面的方法
setContent(content){
setTimeout(()=>{
console.log(13)
content.commit('increment')
},2000)
//执行mutations里面的方法
}
}
}
export default userStore定义方法并引入模块
import { createStore } from 'vuex'
//导入模块文件
import userStore from './userStore'
const store = createStore({
modules:{
// 写入模块
"user":userStore
}
})
export default store;在模块中使用
和之前单模块获取一样,只需要加上模块名就可以了
<template>
<div id="app">
app...
{{count}}
<ul>
{{list}}
<li v-for="item in list" :key="item">{{ item }}</li>
</ul>
<hr/>
<input type="text" placeholder="请输入数据" @keyup.enter="keyUpHandle" v-model="text">
<button @click="addDelay">新增</button>
<router-view/>
</div>
</template>
<script>
// mapState 把vuex中的state数据隐射到组件的计算属性
// mapMutations 把vuex的mutations映射到methods中
// mapActions 把vuex中的actions映射到methods中
import { mapState, mapMutations, mapActions } from 'vuex'
export default {
name: 'App',
data () {
return {
text: ''
}
},
computed: {
...mapState(['count']),
// 第一个参数是命名空间
...mapState('product', ['list'])
},
methods: {
...mapMutations('product', ['add']),
...mapActions('product', ['addAsync']),
keyUpHandle (e) {
if (e) {
this.add(e.currentTarget.value)
}
},
addDelay () {
this.addAsync(this.text)
}
}
}
</script>上面就是关于vuex中modules的使用方法,你看懂了吗?代码下载vuex的下载代码
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧