[Vuejs]-Nested Child objects are not reactive in Vue

0👍

You can simplify the process by using Vue.set and passing/handling the updated fields in the dialog’s event.

<div id="app">
  <v-app id="inspire">
    <div>
      <my-dialog :dialog="dialog" :prop_item="edit_item" @on-update="onUpdate"></my-dialog>

      <v-treeview :items="items.children" item-text="title">
        <template v-slot:prepend="{ item }">
          <v-icon @click.stop="showDialog(item)">mdi-pencil</v-icon>
        </template>
      </v-treeview>
    </div>
  </v-app>
</div>
Vue.component("my-dialog", {
  template: `<v-dialog :value="dialog" persistent><v-card><v-text-field v-model="form.title"></v-text-field></v-card><v-btn @click="$emit('on-update', form)">Save</v-btn></v-dialog>`,
  props: {
    dialog: {},
    prop_item: {}
  },
  data() {
    return {
      form: {
        title: null
      }
    };
  },
  watch: {
    dialog(value) {
      if (value) {
        Object.keys(this.prop_item).forEach((key) => {
          this.$set(this.form, key, this.prop_item[key]);
        });
      }
    }
  }
});

new Vue({
  el: "#app",
  vuetify: new Vuetify(),
  data() {
    return {
      dialog: false,
      edit_item: {},
      items: {
        id: 1,
        title: "Root",
        children: [
          {
            id: 2,
            parentId: 1,
            title: "Chapter 1",
            children: [
              { id: 3, parentId: 2, title: "Sub-chapter 1.1" },
              { id: 4, parentId: 2, title: "Sub-chapter 1.2" }
            ]
          },
          {
            id: 5,
            parentId: 1,
            title: "Chapter 2",
            children: [
              { id: 6, parentId: 5, title: "Sub-chapter 2.1" },
              { id: 7, parentId: 5, title: "Sub-chapter 2.2" }
            ]
          }
        ]
      }
    };
  },
  methods: {
    showDialog(payload) {
      this.edit_item = payload;
      this.dialog = true;
    },

    onUpdate(form) {
      Object.keys(form).forEach((key) => {
        this.$set(this.edit_item, key, form[key]);
      });

      this.dialog = false;
    }
  }
});

Leave a comment