【问题标题】:Custom component two way data-binding updates without emitting event自定义组件双向数据绑定更新而不发出事件
【发布时间】:2020-09-16 09:14:56
【问题描述】:

我正在尝试在自定义组件上实现双向数据绑定(v-model)。
我read the docs 发现了这个:

lovingVue 的值将被传递给 checked 属性。当 发出一个带有新值的更改事件时,lovevVue 属性将被更新。

注意上面写着的部分:property will then be updated when <base-checkbox> emits a change event with a new value

我有一个父组件(HelloWorld.vue),它有一个子组件列表(Note.vue)。每个音符都是可拖动的。父组件有一个表示为对象数组的子组件列表,对于该数组的每个元素,使用 v-for 创建一个 note.vue 实例,并使用 v-model 绑定到数组元素,如下所示:

 <template v-for="(note, index) in notes">
    <note v-model="note.value" :key="note.id" :ref="note.id"></note>
  </template>

并且 note.vue 像这样接受 v-model:

export default {
  name: "Note",
  model: {
    prop: "note",
    event: "even-this-is-not-working"
  },
  props: {
    note: {
      type: Object,
      default: () => null
    }
  },

每当一个注释在内部被拖动到 note 属性的更新属性时(但不会发出更新的注释),但仍会更新父组件中绑定的 note。 (我已经使用 vue 开发工具以及在父组件的注释上添加了一个观察者来验证这一点)。

代码沙盒:https://codesandbox.io/s/custom-v-model-binding-bz61o?file=/src/components/HelloWorld.vue
尝试通过单击Add Note 添加note 并拖动它,即使Note.vue 没有发出任何事件,您也会看到父级中的观察者被触发。

我对这个概念的理解有误吗?还是代码有问题?

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    那是因为你传递对象,而在 JS 中,对象是通过引用传递的。 Note 组件内的 prop note 的内容与 notes[x].value 的标识相同(内存中的相同位置),因此在 Note 组件中对其属性的更新必须在 HelloWorld 父组件中可观察到/p>

    v-model 仅当您希望将notes[x].value 中的对象替换为Note 组件内创建的不同对象时才需要...

    let user = { name: 'John' };
    
    console.log(user.name);
    
    let admin = user; // admin is just reference to existing object
    
    admin.name = 'Pete';
    
    console.log(user.name); // 'Pete', changes are seen from the "user" reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-01
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      相关资源
      最近更新 更多