Creating a tree view from scratch is hard. Therefore, we can make our lives easier with the bootstrap-vue-treeview
library.
We can install it by running:
npm install --save bootstrap-vue-treeview
Then we can use it as follows:
main.js
import Vue from 'vue'
import App from './App.vue'
import BootstrapVueTreeview from "bootstrap-vue-treeview";
Vue.use(BootstrapVueTreeview);
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
App.vue
<template>
<div id="app">
<b-tree-view :data="treeData"></b-tree-view>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
treeData: [
{
id: 2,
name: "toyota",
children: [
{ id: 3, name: "camry" },
{ id: 4, name: "corolla" },
{ id: 5, name: "rav4" },
{ id: 6, name: "prius" }
]
},
{
id: 7,
name: "honda",
children: [
{ id: 8, name: "accord" },
{ id: 9, name: "civic" },
{ id: 10, name: "cub" }
]
}
]
};
}
};
</script>
All we had to do is to register the plugin in main.js
.
Then we add the b-tree-view
component in the template of App.vue
and set the data
prop to the treeData
object, which is returned by the data
method.
In addition to the data
prop, we can also specify the following props:
Prop | Type | Description | Default value | Required |
---|---|---|---|---|
nodeKeyProp |
String | Name of the property containing unique node key | "id" |
No |
nodeChildrenProp |
String | Where to look for node children | "children" |
No |
nodeLabelProp |
String | Name of the property containing node label | "name" |
No |
showIcons |
Boolean | Show/hide icons | false |
No |
iconClassProp |
String | Name of the property containing icon class | "icon" |
No |
defaultIconClass |
String | Icon class to apply if node has no icon class property | null |
No |
prependIconClass |
String | Class to apply to every icon | null |
No |
nodesDraggable |
Boolean | Enable or disable drag & drop feature | false |
No |
contextMenu |
Boolean | Enable or disable context | true |
No |
renameNodeOnDblClick |
Boolean | Enable or disable double click to rename feature | true |
No |
contextMenuItems |
Array of menu items | Context menu items | [ {code: 'DELETE_NODE', label: 'Delete node' }, { code: 'RENAME_NODE', label: 'Rename node' } ] |
No |
With the code we have. we get: