页面中
1.导入vuex
import {
mapGetters, mapMutations } from 'vuex'
2.mapGetters,从vuex里拿数据(me接口的数据)
computed: {
...mapGetters(['isBusiness', 'projects', 'business', 'currentProject', 'currentBusiness']),
},
3.调用方法改变请求头的值
created() {
this.SET_CURRENTPROJECT({
id: '0', title: this.currentBusiness.alias })
},
4.引入方法
methods: {
...mapMutations(['SET_CURRENTPROJECT']),
}
vuex中
user.js
SET_CURRENTPROJECT: (state, project) => {
state.currentProject = project
},
请求拦截,
// request拦截器
service.interceptors.request.use(
config => {
if(config.url.indexOf('!') !== -1){
const type = config.url.split('!')[0]
const url = config.url.split('!')[1]
config.url = server[type] + url
}
if (store.getters.token) {
config.headers['X-Token'] = getToken() // 让每个请求携带自定义token
}
if (store.getters.userinfo && store.getters.userinfo.roleType) {
config.headers['X-RoleType'] = store.getters.userinfo.roleType // 让每个请求携带自定义指挥部类型
}
if (store.getters.business && store.getters.business.type) {
config.headers['X-Type'] = store.getters.business.type // 让每个请求携带自定义用户类型
}
//这里用到这个,改变currentProject(放在请求头里面传给后端)
if (store.getters.currentProject && store.getters.currentProject.id && routes.app.$route.path !== '/dashboard') {
config.headers['X-Project'] = store.getters.currentProject.id // 让带有项目的请求携带自定义项目id
}
return config
},
error => {
// Do something with request error
console.log(error) // for debug
Promise.reject(error)
}
)
getters
const getters = {
sidebar: state => state.app.sidebar,
device: state => state.app.device,
token: state => state.user.token,
userinfo: state => state.user.userinfo,
business: state => state.user.business,
projects: state => state.user.projects,
businesses: state => state.user.businesses,
currentBusiness: state => state.user.currentBusiness,
authorityInfo: state => state.user.authorityInfo,
showNotice: state => state.user.showNotice,
noticeList: state => state.user.noticeList,
menuIndex: state => state.user.menuIndex,
currentProject: state => state.user.currentProject,
weather: state => state.user.weather,
currentPermissions: state => {
if (state.user.currentProject && state.user.currentProject.permissions) {
const permissions = state.user.currentProject.permissions
var json = {
}
permissions.map(item => {
json[item.name] = item
})
return json
} else {
return {
}
}
},
isBusiness: state => (state.user.business.type === 'owner' || state.user.business.type === 'group_owner') && state.user.userinfo.roleType === 'business',
menus: state => state.user.menus,
server_id: state => state.user.server_id,
treeJson: state => state.user.treeJson,
subTree: state => state.user.subTree,
costTab: state => state.user.costTab,
upload_complete: state => state.user.upload_complete,
description: state => state.user.description,
banner: state => state.user.banner,
changeMeasure: state => state.user.changeMeasure,
paragraphId: state => state.user.paragraphId,
todoNumber: state => state.user.todoNumber
}
export default getters