- 目的:知道每個(gè)配置作用,根模塊vue3.0的用法悦昵,帶命名空間模塊在vue3.0的用法
1.根模塊的用法
定義
vue2.0 創(chuàng)建倉庫 new Vuex.Store({})
vue3.0 創(chuàng)建倉庫 createStore({})
export default createStore({
state: {
username: 'zs'
},
getters: {
newName (state) {
return state.username + '!!!'
}
},
mutations: {
updateName (state) {
state.username = 'ls'
}
},
actions: {
updateName (ctx) {
// 發(fā)請(qǐng)求
setTimeout(() => {
ctx.commit('updateName')
}, 1000)
}
},
modules: {
}
})
使用
<template>
<!-- vue2.0需要根元素肴茄,vue3.0可以是代碼片段 Fragment -->
<div>
App
<!-- 1. 使用根模塊state的數(shù)據(jù) -->
<p>{{$store.state.username}}</p>
<!-- 2. 使用根模塊getters的數(shù)據(jù) -->
<p>{{$store.getters['newName']}}</p>
<button @click="mutationsFn">mutationsFn</button>
</div>
</template>
<script>
import { useStore } from 'vuex'
export default {
name: 'App',
setup () {
// 使用vuex倉庫
const store = useStore()
// 1. 使用根模塊state的數(shù)據(jù)
console.log(store.state.username)
// 2. 使用根模塊getters的數(shù)據(jù)
console.log(store.getters.newName)
const mutationsFn = () => {
// 3. 提交根模塊mutations函數(shù)
// store.commit('updateName')
// 4. 調(diào)用根模塊actions函數(shù)
store.dispatch('updateName')
}
return { mutationsFn }
}
}
</script>
2.modules (分模塊)
存在兩種情況
- 默認(rèn)的模塊,state 區(qū)分模塊但指,其他 getters mutations actions 都在全局寡痰。
- 帶命名空間 namespaced: true 的模塊,所有功能區(qū)分模塊枚赡,更高封裝度和復(fù)用。
import { createStore } from 'vuex'
const moduleA = {
// 子模塊state建議寫成函數(shù)
state: () => {
return {
username: '模塊A'
}
},
getters: {
changeName (state) {
return state.username + 'AAAAAA'
}
}
}
const moduleB = {
// 帶命名空間的模塊
namespaced: true,
// 子模塊state建議寫成函數(shù)
state: () => {
return {
username: '模塊B'
}
},
getters: {
changeName (state) {
return state.username + 'BBBBBB'
}
},
mutations: {
// 修改名字的mutation
update (state) {
state.username = 'BBBB' + state.username
}
},
actions: {
update ({ commit }) {
// 假設(shè)請(qǐng)求
setTimeout(() => {
commit('update')
}, 2000)
}
}
}
// 創(chuàng)建vuex倉庫并導(dǎo)出
export default createStore({
state: {
// 數(shù)據(jù)
person: [
{ id: 1, name: 'tom', gender: '男' },
{ id: 2, name: 'lucy', gender: '女' },
{ id: 3, name: 'jack', gender: '男' }
]
},
mutations: {
// 改數(shù)據(jù)函數(shù)
},
actions: {
// 請(qǐng)求數(shù)據(jù)函數(shù)
},
modules: {
// 分模塊
a: moduleA,
b: moduleB
},
getters: {
// vuex的計(jì)算屬性
boys: (state) => {
return state.person.filter(p => p.gender === '男')
}
}
})
使用:
<template>
<div>APP組件</div>
<ul>
<li v-for="item in $store.getters.boys" :key="item.id">{{item.name}}</li>
</ul>
<!-- 使用模塊A的username -->
<p>A的username --- {{$store.state.a.username}}</p>
<p>A的changeName --- {{$store.getters.changeName}}</p>
<hr>
<p>B的username --- {{$store.state.b.username}}</p>
<p>B的changeName --- {{$store.getters['b/changeName']}}</p>
<button @click="$store.commit('b/update')">修改username</button>
<button @click="$store.dispatch('b/update')">異步修改username</button>
</template>