JSFiddle - React, Tailwind, and code Playground
by backstabe
HTML
<!-- item template -->
<script type="text/x-template" id="item-template">
<li>
<div
:class="{bold: isFolder}"
@dblclick="changeType">
<input type="checkbox" :id="model.id" :name="model.id" >
{{ model.name }}
<span v-if="isFolder" @click="toggle">[{{ open ? '-' : '+' }}]</span>
</div>
<ul v-show="open" v-if="isFolder">
<item
class="item"
v-for="(model, index) in model.children"
:key="index"
:model="model">
</item>
</ul>
</li>
</script>
<!-- the demo root element -->
<ul id="demo">
<item
class="item"
:model="treeData">
</item>
<span>IDs: {{ checkedIds }}</span>
</ul>
CSS
body {
font-family: Menlo, Consolas, monospace;
color: #444;
}
.item {
border-top: 1px solid silver;
}
.item span{
cursor: pointer;
}
.bold {
font-weight: bold;
}
ul {
padding-left: 1em;
line-height: 1.5em;
list-style-type: none;
}
Vue
// demo data
var data = {
id: 1,
name: 'My Tree',
children: [
{ id: 2, name: 'hello' },
{ id: 3, name: 'wat' },
{
id: 4,
name: 'child folder',
children: [
{
id: 5,
name: 'child folder',
children: [
{ id: 6, name: 'hello' },
{ id: 7, name: 'wat' }
]
},
{ id: 8, name: 'hello' },
{ id: 9, name: 'wat' },
{
id: 10,
name: 'child folder',
children: [
{ id: 11, name: 'hello' },
{ id: 12, name: 'wat' }
]
}
]
}
]
}
// define the item component
Vue.component('item', {
template: '#item-template',
props: {
model: Object
},
data: function () {
return {
open: false
}
},
computed: {
isFolder: function () {
return this.model.children &&
this.model.children.length
}
},
methods: {
toggle: function () {
if (this.isFolder) {
this.open = !this.open
}
},
changeType: function () {
if (!this.isFolder) {
Vue.set(this.model, 'children', [])
this.addChild()
this.open = true
}
}
}
})
// boot up the demo
var demo = new Vue({
el: '#demo',
data: {
treeData: data,
checkedIds: []
}
})