Answer the question
In order to leave comments, you need to log in
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
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.
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>
<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>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question