因?yàn)樾枰鲆粋€(gè)權(quán)限管理徐伐,所以用到樹(shù)形控件明也。
首先引入組件:
<Tree :data="data4" show-checkbox multiple ref="tree" @on-check-change="choice" class="tree1"></Tree>
<Tree :data="choices" class="tree2"></Tree>
然后是data數(shù)據(jù):
data(){
return{
subdata:[],//用戶半選和全選的數(shù)據(jù)
choices:[],//在右邊需展示出來(lái)的數(shù)據(jù)
power:[],//用戶全選的數(shù)據(jù)
data4:[
{
title:'醫(yī)生',
expand:false,//是否展開(kāi)
children:[
{
title:'看診',
expand:true,
children:[
{
title:'方法'铭段,
expand:true,
children:[
{title:'望'},{title:'聞'},{title:'問(wèn)'},{title:'切'}
]
},
{
title:'寫病歷'
}
]
},
{
title:'開(kāi)藥',
expand:true,
children:[
{ title: '查看藥房庫(kù)存' }, { title: '進(jìn)行開(kāi)藥' }
]
}
]
}
]
數(shù)據(jù)就會(huì)在頁(yè)面上以樹(shù)形結(jié)構(gòu)的形式渲染出來(lái):
樹(shù)形結(jié)構(gòu)
左邊是權(quán)限選項(xiàng)瞧毙,右邊是所選權(quán)限胧华,如何達(dá)到這樣的效果和只獲取用戶所選的權(quán)限寄症。
樹(shù)形控件里提供了三個(gè)事件和三個(gè)方法,這里用到的是事件是@on-select-change矩动,點(diǎn)擊樹(shù)節(jié)點(diǎn)時(shí)觸發(fā)有巧,返回值是當(dāng)前選中的節(jié)點(diǎn)數(shù)組,當(dāng)前項(xiàng)铅忿,用到的方法是getCheckedAndIndeterminateNodes()剪决,用于獲取選中及半選節(jié)點(diǎn)。ref="tree'檀训,這個(gè)屬性一定要寫柑潦,之后要獲取的數(shù)據(jù)通過(guò)$refs.tree.data可獲取。
首先是如何在右邊顯示用戶選擇的權(quán)限峻凫,要有層級(jí)關(guān)系渗鬼,半選的選中的都要顯示。
methods:{
choices(){
console.log("tree.data",this.$refs.tree.data);
this.choices = this.dg(this.$refs.tree.data);
this.subdata=this.$refs.tree.getCheckedAndIndeterminateNodes();//獲取半選和全選的
this.power=this.subdata.filter(item =>{
return !item.children //因?yàn)閒ilter只會(huì)返回true的布爾值荧琼,所以這里把沒(méi)有子集的譬胎,也就是單個(gè)的權(quán)限返回出去,用this.power接收
})
console.log('power',this.power);
},
dg(data){
let s=[];
if(data.children != undefined){
for(let j=0; i<data.children.length; j++){
if(data.children[j].checked || data.children[j].indeterminate){//用到了遞歸命锄,checked ,indeterminate這兩個(gè)屬性是組件上提供的堰乔,
//在瀏覽器上調(diào)試時(shí)可見(jiàn),這是所選控件有子集的時(shí)候脐恩,比如說(shuō)方法下有望聞問(wèn)切四個(gè)子集镐侯,這里是把半選的控件展示上去
s.push({
title:data.children[j].title,
expand:true,
children:this.dg(data.children[j])
});
}
}
}else{
for(let i=0;i<data.length;i++){
if(data[i].checked||data[i].indeterminate){
s.push({
title:data[i].title,
expand:true,
children:this.dg(data[i])
});
}
}
}
console.log(s);
return s;
}
}
將用戶選擇的權(quán)限有層級(jí)關(guān)系的展示出來(lái)后,現(xiàn)在要做的是獲取用戶選擇的權(quán)限驶冒,只需要全選的即可苟翻。這里用到的是iview提供的getCheckedAndIndeterminateNodes()方法。this.power里存放的就是用戶選擇的權(quán)限骗污,然后通過(guò)按鈕保存按鈕提交到后臺(tái)即可
//this.power里存放的就是用戶選擇的權(quán)限崇猫,然后通過(guò)按鈕保存按鈕提交到后臺(tái)即可
this.axios({
method:'post',
url:'/setrole',
data:this.power
}).then(res =>{
console.log(res);
}).catch(err =>){
console.log(err)
}