[英]Sync prop with the parent in Vue?
I would like to have a bidirectional property between a component and its child.我想在组件和它的子组件之间有一个双向属性。 In this example, I have a shared string which is sent to my sub-components:
在这个例子中,我有一个共享字符串发送到我的子组件:
<template>
<div>
<foobar title="Foo" :value.sync="shared"></foobar>
<foobar title="Bar" :value.sync="shared"></foobar>
</div>
</template>
<script>
import Sub from './sub'
export default {
components: {
'foobar': Sub
},
watch : {
shared() {
console.log("Shared value was updated")
}
},
data() {
return {
shared: "Content"
}
}
}
</script>
Each subcomponent is just a text input bound to this shared property:每个子组件只是一个绑定到这个共享属性的文本输入:
<template>
<b-form-group :description="title">
<b-form-input v-model="value"></b-form-input>
</b-form-group>
</template>
<script>
export default {
props: {
value: String,
title: String
}
}
</script>
The expected behaviour is to always see the same value in both text input.预期的行为是始终在两个文本输入中看到相同的值。 If I modify
Foo
, Bar
is updated and the watcher would trig the event Shared value was updated
.如果我修改
Foo
,则Bar
会更新并且观察者会触发事件Shared value was updated
。
I get the error instead:我得到了错误:
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten
whenever the parent component re-enters.
You need to emit event in your child component.您需要在子组件中发出事件。
I didn't test this code but it should look something like this.我没有测试这段代码,但它应该看起来像这样。
<template>
<b-form-group :description="title">
<b-form-input :value="value" @input="$emit('update:value', $event.target.value)"></b-form-input>
</b-form-group>
</template>
<script>
export default {
props: {
value: String,
title: String
}
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.