![](/img/trans.png)
[英]How to assign `value` prop and `v-model` prop to custom Vue component?
[英]Vue how to use v-model on sync prop in child component
在父组件中,我使用.sync
传递一个 prop 来实现 2-way binding,在子组件中,我只是将该 prop 绑定到一个v-model
,这样,我希望子组件的任何更改都可以通过传播到父组件这个.sync
道具。 但是,我收到了警告:
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value.
我做错什么了吗? 根据 vue 文档, .sync
是通过 2-way 数据绑定设计的。 我应该如何在子组件中执行此操作?
孩子不应该在同步的prop
上使用v-model
。 相反,它应该使用$emit('update:<prop>', value)
。 但是,使用父级的v-model
和子级的$emit('input', value)
可能更有意义:
// parent implementation
<child-component v-model="first_name" />
然后,
// child implementation
<template>
<input type="text" @change="$emit('input', e)" :value="innerValue" />
</template>
<script>
export default {
props: ['value'],
data () {
return {
innerValue: ''
}
},
mounted () {
this.innerValue = this.value
}
}
</script>
编辑
如果您想在子组件中使用v-model
方法,则必须在innerValue
上使用它并在更改时发出。 我们可以在孩子中设置一个观察者:
// child component
watch: {
innerValue: function (value) {
this.$emit('input', value)
}
}
然后你可以在你孩子的组件自定义组件实现上使用v-model
:
// child component
<template>
<custom-component v-model="innerValue" />
</template>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.