===============【个人学习记录心得,可供朋友参考】
1:store文件下User获取用户信息中:
import {
login,
logout,
getInfo
} from '@/api/login'
import {
getToken,
setToken,
removeToken
} from '@/utils/auth'
const user = {
state: {
token: getToken(),
name: '',
avatar: '',
roles: [],
buttons: [],
},
mutations: {
SET_TOKEN: (state, token) => {
state.token = token
},
SET_NAME: (state, name) => {
state.name = name
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
},
SET_ROLES: (state, roles) => {
state.roles = roles
},
SET_BUTTONS: (state,buttons)=>{
state.buttons=buttons
}
},
actions: {
// 登录
Login({ commit }, userInfo) {
const username = userInfo.username.trim()
return new Promise((resolve, reject) => {
login(username, userInfo.password).then(response => {
const data = response
setToken(data.access_token)
commit('SET_TOKEN', data.access_token)
resolve()
}).catch(error => {
reject(error)
})
})
},
// 获取用户信息
GetInfo({
commit,
state
}) {
return new Promise((resolve, reject) => {
getInfo(state.token).then(response => {
const data = response.data
if (data.role && data.role.length > 0) { // 验证返回的roles是否是一个非空数组
commit('SET_ROLES', data.role)
} else {
reject('getInfo: roles must be a non-null array !')
}
if(data.buttons.data&& data.buttons.data.length>0){
commit('SET_BUTTONS',data.buttons.data) // 添加按钮权限
}
commit('SET_NAME', data.name)
commit('SET_AVATAR', data.avatar)
resolve(response)
}).catch(error => {
// alert(error + '报错')
reject(error)
})
})
},
// 登出
LogOut({
commit,
state
}) {
return new Promise((resolve, reject) => {
logout(state.token).then(() => {
commit('SET_TOKEN', '')
commit('SET_ROLES', [])
// commit('SET_BUTTONS', []) // 添加按钮权限
removeToken()
resolve()
}).catch(error => {
reject(error)
})
})
},
// 前端 登出
FedLogOut({
commit
}) {
return new Promise(resolve => {
commit('SET_TOKEN', '')
removeToken()
resolve()
})
}
}
}
export default user
图:
:初始化入口过滤按钮 ===
import Vue from 'vue'
import Vuex from 'vuex'
import VueI18n from 'vue-i18n'
import app from './modules/app'
import user from './modules/user'
import permission from './modules/permission'
// import tagsView from './modules/tagsView'
import getters from './getters'
Vue.use(Vuex)
Vue.use(VueI18n)
Vue.directive('has', {
inserted: function (el, binding) {
if (!permissionJudge(binding.value)) {
el.parentNode.removeChild(el);
}
// 过滤按钮
function permissionJudge(value) {
// 此处store.getters.getMenuBtnList代表vuex中储存的按钮菜单数据
let list = user.state.buttons;
for (let item of list) {
if (item.menuOperateId === value.class) {
return true;
}
}
return false;
}
}
})
const store = new Vuex.Store({
modules: {
app,
user,
permission,
// tagsView
},
getters
})
export default store