使用vue.js建構treeview
前言
以前在工作要維護遊戲的後台程式碼,裡面有個treeview,是單純用html與javascript來實現,同步資料時要在不同的幾個地方修改,常常會忘記,最近碰觸到vue.js,發現同步資料相當方便。官方雖然提供了一個範例,但我看不習慣,我修改了其中的部份,這邊做個紀錄。程式碼
以下是html的部分
<head>
<title>treeview example</title>
</head>
<script id="treeview-template" type="text/x-template">
<ul>
<li>
<div @click="onClick">
{{node.name}}
<span v-show="isFolder">[{{isExpand?"-":"+"}}]</span>
</div>
</li>
<treeview v-show="isExpand" v-for="childNode in node.child" :node="childNode"></treeview>
</ul>
</script>
<body>
<div id="app">
<treeview :node="rootNode"></treeview>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</body>
</html>
以下是javascript的部分
var treeNode={
name:"root",
child:[
{
name:"sub"
},
{
name:"sub1",
child:[
{
name:"sub2"
}
]
},
{
name:"sub3"
}
]
};
Vue.component("treeview",{
props : ["node"],
template : "#treeview-template",
data : function(){
return {
isExpand : false
};
},
computed:{
isFolder:function(){
return this.node.child &&
this.node.child.length;
}
},
methods:{
onClick:function(){
if(this.isFolder){
this.isExpand=!this.isExpand;
}
}
}
});
var app = new Vue({
el:"#app",
data:{
rootNode:treeNode
}
});




























