v-model 和 :model-value 之间的区别

ann*_*nna 6 vue.js vuejs3

我想问,因为我仍然很难理解 v-model和之间的区别,:model-value文档中,我读到: v-model is used on a native element:

<input v-model="searchText" />
Run Code Online (Sandbox Code Playgroud)

但是,当我在组件上使用时,v-model会扩展为:

<CustomInput
  :modelValue="searchText"
  @update:modelValue="newValue => searchText = newValue"
/>
Run Code Online (Sandbox Code Playgroud)

好吧,我明白了。但有时我发现,在自定义组件中我们仍然使用:

    <CustomInput
     v-model="searchText" // => why v-model, not :model-value
     @update:modelValue="newValue => searchText = newValue"
   />
Run Code Online (Sandbox Code Playgroud)

所以我有点困惑,为什么,这两个选项之间有什么区别。

Kha*_*ehr 8

基于 Vue.js 文档(链接):

v-model 可以在组件上使用来实现双向绑定。

:prop是 的快捷方式v-bind
例如:
<BlogPost :title="post.title" />与以下完全相同<BlogPost v-bind:title="post.title" />

在自定义组件上v-model只是一个快捷方式:

  :modelValue="value"
  @update:modelValue="newValue => value = newValue"
Run Code Online (Sandbox Code Playgroud)

在本机组件上v-model只是一个快捷方式:

  :modelValue="value"
  @input="newValue => event => value = event.target.value"
Run Code Online (Sandbox Code Playgroud)

v 模型上的 digitalocean

正如您所看到的,与 不同的是v-bindv-model允许从子组件内部更改值。
因此,如果您使用“v-model”,则@update:modelValue="newValue => searchText = newValue"可以删除该行。

请让我知道,如果你有任何问题。