vue3自定义组件使用v-model实现双向数据绑定

一、自定义组件使用 v-model实现双向数据绑定

1.1、单个 v- model 数据绑定
默认情况下,组件上的 v- model 便用 modelvalue 作为 propupdate : modelvalu 作为事件。

<custom-input v-model="searchText"></custom-input>
app.component('custom-input', {
  props: ['modelValue'],
  emits: ['update:modelValue'],
  template: `
    <input
      :value="modelValue"
      @input="$emit('update:modelValue', $event.target.value)"
    >
  `
})

我们可以通过向 v - model 传递参数来修改这些名称:

<my-component  v-model : foo =" bar "></my-component>

在本例中,子组件将需要一 个 foo prop并发出 update : foo 要同步的事件:

   const app = Vue.createApp({})
     app.component ('my-component',{ 
       props:{ 
          foo : String 
       },
    template:` < input  type ="text" :value =" foo"
       @input ="&emit ('update : foo', &event.target.value )">`
     })

1.2、多个v- model 绑定
通过利用以特定 prop 和事件为目标的能力,正如我们们之前在 v-model参数中所学的那样,我们现在可以在单个组件实例上创建多个 v - model 绑定。
每个 v-model 将同步到不同的 prop ,而不需要在组件中添加额外的选项。

 <user-name  v-model:first-name ="firstName" v-model:last-name ="lastName" ></user-name >
    const app = Vue.createApp({})
     app.component ('user-name',{ 
       props:{ 
          firstName : String,
          lastName : String,
       },
    template:` < input   type ="text" :value ="firstName"
        @input ="&emit ('update : firstName', &event.target.value )"> <br/>
        < input    type ="text" :value ="lastName"
        @input ="&emit ('update : lastName', &event.target.value )">
`
     })
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容