Hey everyone, I'm currently working on a Vue project and I have been attempting to create a recursive tree from a flat list. My goal is to toggle the expanded property of each item when clicked, but for some reason, it's not updating.
The issue seems to be occurring within this function:
expandNode(item) {
console.log("HERERERER");
item.expand = false;
this.$set(item, "expand", false);
}
I want my array to be reactive, however, it doesn't seem to be updating. Could it be related to how I'm restructuring the data or is there something else causing the problem? Can someone please take a look at what I've got so far?
Here is the link to my CodeSandbox demo:
https://codesandbox.io/s/condescending-tree-51rbs
This is the code snippet for the component:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<tr v-for="(item ,index) in flatArray" :key="index">
<div class="item" @click="expandNode(item)">
<div class="element" v-show="item.expand">
{{ item.expand }}
<span>{{ item.label }}</span>
</div>
</div>
</tr>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: String,
data: { default: () => null, type: Array }
},
data() {
return {
flatArray: []
};
},
mounted() {
let arr = [];
console.log("HERERER");
this.recursive(this.data, arr, 0, null, -1);
this.flatArray = arr;
console.log(this.flatArray);
},
computed: {
setPadding(item) {
return `padding-left: ${item.level * 30}px;`;
}
},
methods: {
recursive(obj, newObj, level, parent, parentIndex) {
obj.forEach(node => {
if (node.children && node.children.length != 0) {
node.level = level;
node.leaf = false;
node.expand = true;
node.parent = parent;
node.parentIndex = parent ? parentIndex : null;
newObj.push(node);
this.recursive(
node.children,
newObj,
node.level + 1,
node,
newObj.indexOf(node)
);
} else {
node.level = level;
node.leaf = true;
node.expand = true;
node.parent = obj;
node.parentIndex = parent ? parentIndex : null;
newObj.push(node);
return false;
}
});
},
expandNode(item) {
console.log("HERERERER");
item.expand = false;
this.$set(item, "expand", false);
}
}
};
</script>