JSFiddle - React, Tailwind, and code Playground
by cmaai
HTML
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<!-- item template -->
<script type="text/x-template" id="item-template">
<li>
<div
:class="{bold: isFolder}"
@click="toggle"
@dblclick="changeType">
<span v-if="isFolder">[{{ open ? '-' : '+' }}]</span>
{{ model.name }}
</div>
<ul v-show="open" v-if="isFolder">
<item
class="item"
v-for="(model, index) in model.children"
:key="index"
:model="model">
</item>
<li class="add" @click="addChild">+</li>
</ul>
</li>
</script>
<p>(You can double click on an item to turn it into a folder.)</p>
<!-- the demo root element -->
<ul id="demo" class = "domtree">
<item
class="item"
:model="treeData">
</item>
</ul>
CSS
body {
font-family: Menlo, Consolas, monospace;
color: #444;
}
.item {
cursor: pointer;
}
.bold {
font-weight: bold;
}
ul.domtree, ul.domtree ul {
margin: 0;
padding: 0 0 0 2em;
}
ul.domtree li {
list-style: none;
position: relative;
}
ul.domtree li:before {
position: absolute;
content: '';
top: -0.1em;
left: -0.5em;
width: 0.4em;
height: 0.615em;
border-style: none none solid dashed;
border-width: 0.05em;
}
ul.domtree li:not(:last-child):after {
position: absolute;
content: '';
top: 0;
left: -0.5em;
bottom: 0;
border-style: none none none dashed;
border-width: 0.05em;
}
JavaScript
// demo data
var data = {
name: 'My Tree',
children: [
{ name: 'hello' },
{ name: 'wat' },
{
name: 'child folder',
children: [
{
name: 'child folder',
children: [
{ name: 'hello' },
{ name: 'wat' }
]
},
{ name: 'hello' },
{ name: 'wat' },
{
name: 'child folder',
children: [
{ name: 'hello' },
{ name: 'wat' }
]
}
]
}
]
}
// define the item component
Vue.component('item', {
template: '#item-template',
props: {
model: Object
},
data: function () {
return {
open: true
}
},
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 = false
}
},
addChild: function () {
this.model.children.push({
name: 'new stuff'
})
}
}
})
// boot up the demo
var demo = new Vue({
el: '#demo',
data: {
treeData: data
}
})