Vue uses v-model on components
Custom events can also be used to create a support v-model
custom input components. remember:
<input v-model="searchText">
Equivalent to:
<input
:value="searchText"
@input="searchText = $event.target.value"
>
When used on a component, v-model
it will look like this:
<custom-input
:value="searchText"
@input="searchText = $event"
></custom-input>
Above with
$event
the receiving sub-assembly for$emit()
transmitting data over the upwardly
To make it work, within this component <input>
must:
- To
value
attribute bound to a namevalue
on the prop - In its
input
event is triggered, the new value through custominput
event 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-model
you 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: ""
}
})