Vue在组件上使用v-model

Vue在组件上使用v-model

自定义事件也可以用于创建支持 v-model 的自定义输入组件。记住:

<input v-model="searchText">

等价于:

<input
  :value="searchText"
  @input="searchText = $event.target.value"
>

当用在组件上时,v-model 则会这样:

<custom-input
  :value="searchText"
  @input="searchText = $event"
></custom-input>

上面用 $event 接收子组件用 $emit() 向上传递过来的数据

为了让它正常工作,这个组件内的 <input> 必须:

  • 将其 value attribute 绑定到一个名叫 value 的 prop 上
  • 在其 input 事件被触发时,将新的值通过自定义的 input 事件抛出

写成代码之后是这样的:

Vue.component('custom-input', {
    
    
  props: ['value'],
  template: `
    <input
      :value="value"
      @input="$emit('input', $event.target.value)"
    >
  `
})

现在 v-model 就应该可以在这个组件上完美地工作起来了:

<custom-input v-model="searchText"></custom-input>

以下是更简化代码,我发现不用写 :value这个属性也能正常的实现数据的双向绑定

<div id="app">
    <input-com v-model="username"></input-com>
    <h1>{
   
   { username }}</h1>
</div>
Vue.component("input-com",{
    
    
    // 当用户输入数据的时候把value值传递给父组件
    template: `<input @input="$emit('input',$event.target.value)" />`,
})
var app = new Vue({
    
    
    el: "#app",
    data: {
    
    
        username: ""
    }
})

猜你喜欢

转载自blog.csdn.net/Cool_breeze_/article/details/109412029