将新项目/文件夹添加到树视图 - VueJS + Vuetify



我正在尝试将新项目添加到我使用 Vuetify 布局创建的树视图中。源代码在这里:https://codepen.io/luizarusso/pen/YzPqNpy

methods: {    
addChildFile(item) {
if (!item.children) {
this.$set(item, "children", []);
}
const name = 'kkk';
const file = 'pdf';
item.children.push({
name,
file
});
},
addChildFolder(item) {
if (!item.children) {
this.$set(item, "children", []);
}
const name = 'kkk';
const id = this.nextId++;
item.children.push({
id,
name
});
},
}

它工作正常!但是我需要提供一个对话框,用户应该在其中选择要上传的文件或插入文件夹名称。此时,当我尝试在子节点内插入时,我会丢失要插入新文件/文件夹的节点的索引。

这是我得到的最接近的:https://codepen.io/luizarusso/pen/dyPORda

methods: {    
addFile (item) {
this.editedIndex = this.items.indexOf(item)
this.editedItem = Object.assign({}, item)
this.dialog = true
},
addFolder (item) {
this.editedIndex = this.items.indexOf(item)
this.editedItem = Object.assign({}, item)
this.dialog2 = true
},
addChildFile() {
if (!this.editedItem.children) {
this.$set(this.editedItem, "children", []);
}
const id = this.nextId++;
const name = this.fd[0].name;
const file = 'pdf';
this.editedItem.children.push({
id,
name,
file
});
this.dialog = false
},
addChildFolder() {
if (!this.editedItem.children) {
this.$set(this.editedItem, "children", []);
}
const name = this.nomePasta;
const id = this.nextId++;
this.editedItem.children.push({
id,
name
});
this.dialog2 = false
},
}

有没有办法保持绑定?有什么想法吗? 多谢!

编辑: Djip的回答解决了这个问题。这是解决方案的源代码,以防有人想看:https://codepen.io/luizarusso/pen/MWYbZVP 正如他所解释的,你只需要使用 = 符号将 editedItem 变量设置为正确的项目,而不是它的副本(使用 Object.assign 时(

addFile (item) {
this.editedIndex = this.items.indexOf(item)
this.editedItem = item
this.dialog = true
},
addFolder (item) {
this.editedIndex = this.items.indexOf(item)
this.editedItem = item
this.dialog2 = true
},

干杯!

问题是你使用的是Object.assign({}, item);.Object.assign做什么,它复制对象,并删除引用。

因此,您应该将代码更改为以下内容:

methods: {    
addFile (item) {
this.editedIndex = this.items.indexOf(item)
this.editedItem = item
this.dialog = true
},
addFolder (item) {
this.editedIndex = this.items.indexOf(item)
this.editedItem = item
this.dialog2 = true
},

这样,您将editedItem变量设置为正确的项目,而不是它的副本。

最新更新