前一篇文章我寫了怎麼控制菜單權限和內容權限,但是那些都是寫死的,不夠靈活,在工作中的需求有很多是滿足不了的,今天我再講講我說怎麼從後端獲取權限來展示我們每個用戶不同的內容。
1、首先我們後臺數據我用了端json數據來模擬,存放在public文件夾下面。
數據的內容如下:
{
"admin":
{
"User":{"one":true,"two":false,"three":true,"box_a":true,"box_b":false,"box_c":true,"admin_one":true,"admin_two":true,"admin_three":true,"list":"<Button class='ant-btn ant-btn-primary'>獲取菜單1</Button><span>獲取內容2</span><h1>獲取菜單3</h1><Button class='ant-btn ant-btn-primary'>獲取內容4</Button>"},
"User_a":{"boxa1":true,"boxa2":true,"fetr":true}
},
"user" :
{
"User":{"one":false,"two":true,"three":true,"box_a":true,"box_b":true,"box_c":true,"list":""},
"User_u":{"test1":true,"test2":true,"test3":true,"from":true},
"Lets":{"list1":true,"list2":false,"list3":true}
}
}
解釋一下這些數據:首先是一個對象中有admin和user兩個用戶,在admin用戶下有User和User_a兩個頁面,在user用戶下有User、User_u和Lets三個頁面。
在admin用戶下的User頁面中組件one可顯示,組件two不顯示,組件three顯示,組件box_a顯示,組件box_b不顯示,組件box_c顯示,跳轉頁面的組件admin_one顯示,組件admin_two顯示,組件admin_three顯示,list是存儲的菜單的string直接渲染到頁面。其他頁面也是如此。
我們再來看看代碼
constructor(props) {
super(props);
this.state = {
str: [],
list: ""
}
this.isPoss = this.isPoss.bind(this)
this.goOrder = this.goOrder.bind(this)
}
componentWillMount() {
this.isPoss()
}
isPoss() {
const _this = this
let arr = getAuthority()
const us = getAuthority()
axios.get('http://localhost:8000/data.json').then((res) => {
let arrs = res.data[us].User
let lists = res.data[us].User.list
for (var i in arrs) {
if (arrs[i]) {
arr.push(i)
}
}
_this.setState({
str: arr,
list: lists
})
}).catch((err) => {
console.log(err.status);
})
return _this.state.rees
}
//頁面跳轉+傳遞參數
goOrder() {
this.props.dispatch(routerRedux.push({
pathname: '/system/user/user_a/user_admin',
params: this.state.str
}))
}
這裏’http://localhost:8000/data.json’就是將json文件放入public文件夾下然後請求的地址,這時候你如果是打開項目的,直接訪問這個地址就能訪問到json文件。
這裏我採用了在組件中訪問,並且把方法綁定到了componentWillMount()中,並且我是在組件中的render()方法中才創建的權限組件Authorized
這時候你纔不用考慮請求的同步和異步,否則你在組件外請求數據你就得用同步請求,然而我們知道同步請求可不是一個好的方法。
至於組件的書寫我這裏就不寫了,大致是配合我之前寫的權限的使用。我們來看一下效果。
admin用戶的
user用戶的