javascript - Vue中的两种数据绑定:无法从子组件更新父组件
问题描述
我得到以下两个组件:
家长:
<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 ,我应该使用更新和同步将道具从孩子传递回父母。但是它不起作用。我不明白这里出了什么问题。我错过了什么?
解决方案
通常最好不要将模板绑定到道具,而是绑定到计算属性,以确保在外部访问和修改数据。它还将稍微简化您的代码,以便您不必触发更新。
家长:
<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>
推荐阅读
- c# - 包裹在按钮中的矩形不会触发命令
- python - 返回数组中某个概率以上值的排序索引
- java - 如何连接 2 onActivityResult?
- django - 当我尝试转到 /accounts/login 时,allauth 将我重定向到 /accounts/profile
- python - 从 Celery 任务中获取全部数据
- python - 如何找到每个字母在名称中出现的次数?
- java - Mockito mockingDetails.getInvocations() 问题
- javascript - 如何在axios post请求中传递formData和body参数
- amazon-web-services - Firehose 无法在 Terraform 上承担角色错误
- vb.net - 使用 VB.net 下载文件