1. Can v-model be used on custom components? If so, how to use it?
Can. v-model is actually a syntactic sugar, such as:
<input v-model="searchText">
is actually equivalent to:
<input
v-bind:value="searchText"
v-on:input="searchText = $event.target.value"
>
The same is true for custom components:
<custom-input v-model="searchText">
equivalent to
<custom-input
v-bind:value="searchText"
v-on:input="searchText = $event"
></custom-input>
Obviously, the interaction between custom-input and the parent component is as follows: 1. The parent component passes the searchText variable to the custom-input component, and the prop used is named value; 2. The custom-input component transmits an event named input to the parent component, and the parent component Assign the received value to searchText; therefore, the implementation of the custom-input component should look like this:
Vue.component('custom-input', {
props: ['value'],
template: `
<input
v-bind:value="value"
v-on:input="$emit('input', $event.target.value)"
>
`
})