v-model的本质
v-model是v-bind:vlaue和v-on:input的语法糖
<div id="app">
<!-- <input type="text" v-model="number"> -->
<input type="text" v-bind:value="number" v-on:input="number=$event.target.value">
{{number}}
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
<script>
let app = new Vue({
el: "#app",
data:{
number: 0
}
})
</script>
v-model在组件中使用
<div id="app">
{{number}}
<!-- <my-component :value='number' @input="number=$event"></my-component> -->
<my-component v-model="number"></my-component>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
<script>
Vue.component('my-component',{
props:['value'],
template: `<div><button @click="$emit('input', ++value)">+1</button></div>`
})
let app = new Vue({
el: "#app",
data:{
number: 0
}
})
</script>
v-model在render函数中使用
<div id="app">
{{number}}
<my-component v-model="number"></my-component>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.js"></script>
<script>
Vue.component('my-component',{
render(createElement){
let self = this
return createElement('input', {
domProps:{
value: self.value
},
on:{
input(event){
self.$emit('input',event.target.value)
}
}
})
}
})
let app = new Vue({
el: '#app',
data:{
number: 0
}
})
</script>