将新的 items/folders 添加到 TreeView - VueJS + Vuetify

add new items/folders to a TreeView - 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
      });
    },
}

效果很好!但是我需要提供一个对话框,用户应该在其中 select 要上传的文件或插入文件夹名称。此时,当我尝试插入子节点时,我丢失了要插入新节点的索引 file/folder.

这是我得到的最接近的: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 变量设置为正确的项目,而不是其副本。