1. Vuex命名空间解决的问题
- 模块命名冲突:在大型Vue项目中,不同功能模块可能有相同命名的状态、mutations、actions等。例如,用户模块和订单模块都可能有
loading
状态,如果不使用命名空间,就会产生冲突。使用命名空间可避免这种情况,每个模块都有自己独立的命名空间。
- 代码结构清晰:使代码结构更清晰,便于维护和理解。例如,将用户相关的所有Vuex操作放在
user
命名空间模块下,订单相关放在 order
命名空间模块下,开发者能快速定位到所需代码。
2. 代码实现
模块定义
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
user: {
namespaced: true,
state: () => ({
name: '',
age: 0
}),
mutations: {
SET_NAME(state, newName) {
state.name = newName
}
},
actions: {
asyncUpdateName({ commit }, newName) {
// 模拟异步操作
setTimeout(() => {
commit('SET_NAME', newName)
}, 1000)
}
}
},
order: {
namespaced: true,
state: () => ({
orderList: []
}),
mutations: {
ADD_ORDER(state, newOrder) {
state.orderList.push(newOrder)
}
},
actions: {
asyncAddOrder({ commit }, newOrder) {
// 模拟异步操作
setTimeout(() => {
commit('ADD_ORDER', newOrder)
}, 1000)
}
}
}
}
})
export default store
访问模块状态
<template>
<div>
<p>User Name: {{ $store.state.user.name }}</p>
<p>Order List Length: {{ $store.state.order.orderList.length }}</p>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
触发mutations
<template>
<div>
<button @click="updateUserName">Update User Name</button>
<button @click="addOrder">Add Order</button>
</div>
</template>
<script>
export default {
methods: {
updateUserName() {
this.$store.commit('user/SET_NAME', 'New User Name')
},
addOrder() {
this.$store.commit('order/ADD_ORDER', { id: 1, product: 'Product 1' })
}
}
}
</script>
触发actions
<template>
<div>
<button @click="asyncUpdateUserName">Async Update User Name</button>
<button @click="asyncAddOrder">Async Add Order</button>
</div>
</template>
<script>
export default {
methods: {
asyncUpdateUserName() {
this.$store.dispatch('user/asyncUpdateName', 'New Async User Name')
},
asyncAddOrder() {
this.$store.dispatch('order/asyncAddOrder', { id: 2, product: 'Product 2' })
}
}
}
</script>