У меня есть следующие два компонента:
Родитель:
<template>
<v-container>
<v-row class="text-center">
<v-col cols="12" class="parent">
<p>Ich bin der Parent component</p>
<button @click="changeDetail" :name.sync="name">Change Details</button>
<Child v-bind:name="name"></Child>
</v-col>
</v-row>
</v-container>
</template>
<script>
import Child from "./Child";
export default {
name: "Parent",
data: () => ({
name: "test"
}),
methods: {
changeDetail() {
this.name = "Updated from Parent";
}
},
components: {
Child
}
};
</script>
Ребенок:
<template>
<v-container>
<v-row class="text-center">
<v-col cols="12">
<p>My name is: {{ name}}</p>
<button @click="resetname">Reset the name</button>
</v-col>
</v-row>
</v-container>
</template>
<script>
export default {
// props: ["name"],
props: {
name: {
type: String,
required: true
}
},
data: () => ({
newname: "Updated from Child"
}),
methods: {
resetname() {
this.$emit("update:name", this.newname);
}
}
};
</script>
Насколько я читал здесь: https://vuejs.org /v2/guide/components-custom-events.html#sync-Modifier, я должен использовать update и sync, чтобы передать реквизиты от дочернего элемента обратно к родительскому. Однако это не работает. Я не понимаю, что здесь не так. Что мне не хватает?
1 ответ
Обычно лучше не привязывать свой шаблон к опоре, а к вычисляемому свойству, чтобы обеспечить доступ к данным и их изменение извне. Это также немного упростит ваш код, так что вам не придется запускать обновления.
Родитель:
<template>
<v-container>
<v-row class="text-center">
<v-col cols="12" class="parent">
<p>Ich bin der Parent component</p>
<button @click="changeDetail">Change Details</button>
<Child v-bind:name.sync="name"></Child>
</v-col>
</v-row>
</v-container>
</template>
<script>
import Child from "./Child";
export default {
name: "Parent",
data: () => ({
name: "test"
}),
methods: {
changeDetail() {
this.name = "Updated from Parent";
}
},
components: {
Child
}
};
</script>
Ребенок:
<template>
<v-container>
<v-row class="text-center">
<v-col cols="12">
<p>My name is: {{ currentName }}</p>
<button @click="resetname">Reset the name</button>
</v-col>
</v-row>
</v-container>
</template>
<script>
export default {
// props: ["name"],
props: {
name: {
type: String,
required: true
}
},
data: () => ({
//Be careful with fat arrow functions for data
//Because the value of *this* isn't the component,
//but rather the parent scope.
}),
computed: {
currentName: {
get() { return this.name },
set(value) { this.$emit("update:name", value); }
}
},
methods: {
resetname() {
this.currentName = "updated from child";
}
}
};
</script>
Похожие вопросы
Новые вопросы
javascript
По вопросам программирования на ECMAScript (JavaScript / JS) и его различных диалектах / реализациях (кроме ActionScript). Включите все соответствующие теги в свой вопрос; например, [node.js], [jquery], [json] и т. д.