繁体   English   中英

Vue如何在子组件的同步道具上使用v-model

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM