Vue uses v-model on components

Vue uses v-model on components

Custom events can also be used to create a support v-modelcustom input components. remember:

<input v-model="searchText">

Equivalent to:

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

When used on a component, v-modelit will look like this:

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

Above with $eventthe receiving sub-assembly for $emit()transmitting data over the upwardly

To make it work, within this component <input>must:

  • To valueattribute bound to a name valueon the prop
  • In its inputevent is triggered, the new value through custom inputevent thrown

After writing the code, it looks like this:

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

Now v-modelyou should be able to work perfectly up on this component:

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

The following is a more simplified code, I found that the two-way binding of data can be implemented normally without writing: 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: ""
    }
})

Guess you like

Origin blog.csdn.net/Cool_breeze_/article/details/109412029