Vue 里面对树状数组进行增删改查 的方法
[
{
"id":"5e4c3b02fc984961a17607c37712eae0", "optLock":0, "parentId":"31372c5ce7c84eb1862c21b5af85b4d2", "name":"1111", "type":0, "subCatalogues": [
{
"id":"7bf755f26c0e499898504a34877a4fce", "optLock":0, "parentId":"5e4c3b02fc984961a17607c37712eae0", "name":"3333", "type":0, "subCatalogues":[
{
"id":"2b08b56ab72641ffa1373813082e95c5", "optLock":0," parentId":"7bf755f26c0e499898504a34877a4fce", "name":"4444", "type":1," subCatalogues":null } ] } ] },
{
"id":"dcf5854558ae47e7b52918c4af861385", "optLock":0, "parentId":"31372c5ce7c84eb1862c21b5af85b4d2", "name":"2222", "type":0, "subCatalogues":[
{
"id":"7acad754831b4b81b87bff33d6090166", "optLock":0, "parentId":"dcf5854558ae47e7b52918c4af861385", "name":"5555", "type":0, "subCatalogues":[
{
"id":"4eb8db6f27f644b28a8c791208f55946", "optLock":0, "parentId":"7acad754831b4b81b87bff33d6090166", "name":"6666", "type":1, "subCatalogues":null }
]
上面是数据结构, 方法实现的目的,通过传入的 parentId 找到父级,向父级的subCatalogues添加 一个对象
handleLocalData(pId) { return findPidNode(this.data) //这里的data 数据就是 上面的数组 function findPidNode(data) { data = data ? data : [] for (let i = 0, n = data.length; i < n; i++) { let node = findInTree(data[i]) if (node) { return node //这里得到的就是 parentId 得到的父级对象 } } } function findInTree(tree) { if (tree.id == pId) { return tree } else { return findPidNode(tree.subCatalogues) } } }
通过数组是引用数据类型特征,改变数据结构就能引起 this.data 里面数据的变化,从而引起ui 图的跟新
如何使用 handleLocalData() 方法(这里删除来说):
let node = this.handleLocalData(this.parentId) //这里得到的this.parentId就是上面数据结构里面的 parentId,因为我通过ui 组件单独他它给列出来啦 if (node) { //这里判断是因为 在顶级的数组是没有parentId 的 ,如果没有父级 就需要想同级添加了,而不是添加到 subCatalogues 里面 let index = node.subCatalogues.findIndex( e => e.id == this.parentId ) node.subCatalogues.splice(index, 1) } else { let index2 = 0 this.data.forEach((item, index) => { if (item.id == this.parentId) { index2 = index } }) this.data.splice(index2, 1) }