紧接上篇:
本篇记录vue3 vuex actions的使用,默认进行了模块化的管理,开启了命名空间
目录:
user.js?
const user = {
namespaced: true, //开启命名空间 建议开启
state: {
name: '',
token: 'token 123456789',
sex: 2, //0=>代表女 | 1=>代表男 | 2=>代表保密
role: null //用户角色
},
mutations: {
setUserRole(state, role) {
state.role = role
}
},
actions: {
async getUserRole({state, commit}, payload) {
function httpRole(data) {
console.log('请求参数===>', data) //模拟请求参数
return new Promise((resolve) => {
setTimeout(() => {
resolve(['admin', 'add'])
}, 300)
})
}
let resp = await httpRole({token: state.token, id: payload}) //模拟请求
commit('setUserRole', resp)
}
}
}
export default user
index.js
import {createStore} from 'vuex'
import user from "./modules/user";
// 创建一个新的 store 实例
const store = createStore({
strict: process.env.NODE_ENV !== 'production', //在开发状态下开启严格模式
modules: {
user
}
})
export default store
页面,Test.vue
<template>
<div>{{ role }}</div>
<button @click="getRole">获取当前用户角色</button>
</template>
<script>
import {computed} from 'vue'
import {useStore} from "vuex"
export default {
name: "Test",
setup() {
let {state, dispatch} = useStore();
function getRole() {
dispatch('user/getUserRole', 999)
}
return {
role: computed(() => state.user.role),
getRole
}
}
}
</script>
点击获取用户角色按钮:
|