Vue组件上的数据双向绑定

114 阅读1分钟

vue2中在组件上实现双向数据绑定,一般使用.sync修饰符。vue3中则去除掉这个修饰符,进而把功能集成到了v-model上。

sync在vue2中的用法

可能需要对一个 prop 进行“双向绑定”。因为真正的双向绑定会带来维护上的问题,因为子组件可以变更父组件,且在父组件和子组件两侧都没有明显的变更来源。推荐以 update:myPropName 的模式触发事件取而代之。

父组件调用子组件用法:

<text-document v-bind:title.sync="doc.title"></text-document>

将被分解为

<text-document v-bind:title="doc.title" v-on:update:title="doc.title = $event" ></text-document>

然后在子组件中发起对应的事件,即可修改父组件的数据,实现数据的双向绑定。

v-model在Vue3中的用法

而当使用在一个组件上时,v-model 会被展开为如下的形式

<CustomInput :modelValue="searchText" @update:modelValue="newValue => searchText = newValue"/>

要让这个例子实际工作起来,<CustomInput> 组件内部需要做两件事:

  1. 将内部原生 input 元素的 value attribute 绑定到 modelValue prop
  2. 输入新的值时在 input 元素上触发 update:modelValue 事件

v-model中有参数。默认情况下,v-model 在组件上都是使用 modelValue 作为 prop,并以 update:modelValue 作为对应的事件。一个组件上可以有多个v-model绑定,每一个 v-model 都会同步不同的 prop。