M
M
mikhail_fishtank2021-05-31 18:37:02
Vue.js
mikhail_fishtank, 2021-05-31 18:37:02

What is the best way to organize data communication between child components and parent?

There are two components - a parent component that describes, for example, a catalog of books, and a child component that describes a book. You need to display books in the catalog.
How should book data be stored?
- In the parent component, the child components do not have separate data, data as part of the parent data, for example, some kind of booksList field.
- In child components, each has its own set of data, nothing in the parent.
- Somehow smeared between parent and child.
And what should it look like in code so that the data stays linked?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MikUrrey, 2021-05-31
@MikUrrey

In the parent component, the child components do not have separate data, data as part of the parent data, for example, some kind of booksList field.

Rather, in the parent component for the book catalog, but lower down deeper in the form of props.
And what should it look like in code so that the data stays linked?

<template>
  <lib-category v-model="booksList"></lib-category>
</template>
<script>
import libCategory from "./libCategory.vue"
default export {
  //...
  components: {libCategory},
  data() {
    return {
      booksList: [],
    }
  }
  //...
}
</script>

libCategory.vue
<template>
  <div v-for="(category, i) in booksListInner" :key="'i' + i">
     <!-- тут какое-то оформление категории -->
     ...
     <!-- а тут перечисляем книги, в нее входящие -->
     <lib-book v-for="(book, k) in category.children" :key="'k' + k" v-model="book"></lib-book>
  </div>
</template>
<script>
import libBook from "./libBook.vue"
default export {
  //...
  props: ['value'],
  components: {libBook},
  data() {
    return {
      booksListInner: [],
    }
  },
  watch: {
    value: {
      handler (value) { //связанность снаружи внутрь
        this.booksListInner = value
      },
      immediate: true,
      deep: true, //необходимо для объекта с вложенностью
    },
    booksListInner: {
      handler (booksListInner) { //связанность изнутри наружу
        this.$emit("input", booksListInner)
      },
      deep: true, //необходимо для объекта с вложенностью
    }
  }
}
</script>

libBook.vue is similar.
I do not know all the features of your list, I proceed from a minimal understanding. Depending on the data structure, there may be nuances in reactivity when new elements are added.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question