Vue封裝樹形選單元件
阿新 • • 發佈:2019-02-16
csdn終於更新完成了哈,ok,步入正題
像這種樹形結構的核心思想就是:遞迴思想,知道使用遞迴,其實這個例子函式的封裝也就很簡單嘍
實現步驟:
設定的props:
data 資料結構 預設為 []
定製模板:
不可定製
監控狀態變化:
事件名on-select-change 點選樹節點觸發
使用:在需要的地方插入形如下面的程式碼,
<m-tree :data="treeList"></m-tree>
你的資料結構應該是下面的型別:
傳入的資料結構:
[
{
title:XXX,
children:[
{
title:XXXX,
chidren:[]
}
]
}]
如下示例:
var data = [{ title: "目錄", chidren: [{ title: "我的音樂", chidren: [{ title: "周杰倫", chidren: [{ title: "發如雪" }] }, { title: "王傑", chidren: [{ title: "一場遊戲一場夢" }] }] }, { title: "我的照片" }] }];
利用vue封裝了一個樹形選單元件,效果圖如下:
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style>
ul {
padding: 0;
margin: 0;
list-style: none;
}
.tree-menu {
width: 360px;
height: 100%;
padding: 0px 12px;
border-right: 1px solid #e6e9f0;
}
.tree-menu-comm span {
display: block;
font-size: 12px;
position: relative;
}
.tree-contro .ico {
background-position: 3px -92px;
}
.tree-title .ico {
position: absolute;
left: -13px;
top: 0;
width: 15px;
height: 26px;
background: url(./folder-tree.png) no-repeat 4px -43px;
opacity: 0.8;
}
.tree-menu-comm span strong {
display: block;
width: 82%;
position: relative;
line-height: 22px;
padding: 2px 0;
padding-left: 5px;
color: #161719;
font-weight: normal;
}
.tree-nav {
background: #e7f2fe;
border: 1px solid #bfdaf4;
padding-left: 14px;
margin-left: 0px;
}
.tree-title {
border: 1px solid #fff;
margin-top: 1px;
}
/*無箭頭*/
.tree-contro-none .ico {
background-position: -999px -99px;
}
/*箭頭朝下*/
.tree-contro .ico {
background-position: 3px -92px;
}
</style>
<script src="../vue.js"></script>
<script>
</script>
</head>
<body>
<div id="app">
<j-costum :data="treeList"></j-costum>
</div>
<script>
var data = [{
title: "目錄",
chidren: [{
title: "我的音樂",
chidren: [{
title: "周杰倫",
chidren: [{
title: "發如雪"
}]
}, {
title: "王傑",
chidren: [{
title: "一場遊戲一場夢"
}]
}]
}, {
title: "我的照片"
}]
}];
Vue.component("j-tree-list",{
computed:{
count(){
var c = this.increment;
return ++c;
},
stylePadding(){
return {
'padding-left':this.count * 16 + 'px'
}
}
},
props:{
data:{
type:Array,
default:[]
},
increment:{
type:Number,
default:0
}
},
data:function(){
return {
fold:true
}
},
template:`
<ul>
<li v-for="item in data">
<div class="tree-title" :style="stylePadding">
<span>
<strong>{{item.title}}</strong>
<i class="ico"
@click="foldFn(item)"
></i>
</span>
</div>
<j-tree-list
:increment="count"
v-if="item.chidren"
v-show="fold"
:data="item.chidren"></j-tree-list>
</li>
</ul>
`,
methods:{
foldFn(item){
this.fold = !this.fold;
}
}
})
Vue.component("j-costum",{
props:{
data:{
type:Array,
default:[]
}
},
template:`
<div class="tree-menu-comm tree-menu">
<j-tree-list :data="data"></j-tree-list>
</div>
`
})
var vm = new Vue({
el:"#app",
data:{
treeList:data
}
});
</script>
</body>
</html>