<input v-model="searchText">
Equivalent to
<input v-bind:value="searchText" v-on:input="searchText = $event.target.value" >
When used on components, v-model does this:
<custom-input v-model="searchText"></custom-input>
Equivalent to
<custom-input v-bind:value="searchText" v-on:input="searchText = $event" ></custom-input>
In order for it to work properly, <input> within this component must:
- Bind its value feature to a prop called value
- When its input event is triggered, the new value is thrown through a custom input event
Vue.component('custom-input', { props: ['value'], template: ` <input v-bind:value="value" v-on:input="$emit('input', $event.target.value)" > ` })
Now the v-model should work perfectly on this component:
<custom-input v-model="searchText"></custom-input>
Example
In the parent component App.vue
<template> <div id="app"> <Model v-model="searchText"></Model> <span>{{searchText}}</span> <!-- Equivalent to <custom-input v-bind:value="searchText" @input="searchText = $event" ></custom-input> --> </div> </template> <script> import Model from "./components/Model"; export default { name: "App", data: function() { return { searchText:'' }; }, components: { Model } }; </script>
Subcomponent model.vue
<template> <div id="app"> <input v-bind:value="value" @input="$emit('input', $event.target.value)"> </div> </template> <script> export default { props: ["value"], }; </script>
Process:
1. Input text
2.:value='search'passed to the subcomponent
3. Subcomponent props reception
4. Subcomponents: value='value'
5. The child component binding input is passed to the parent component through $emit
6. The parent component @input='searchText= $event'receives