<div id="app">
<custom-input v-model="father"></custom-input>
<span>{{father}}</span>
</div>
<script>
Vue.component('custom-input', {
template: `
<div @click='add'>add</div>
`,
data(){
return{
a:1
}
},
methods: {
add() {
this.$emit('input',this.a++)
}
}
})
new Vue({
el: "#app",
data: {
father: 'when you click add ,here will change'
},
})
</script>
如上代码为什么传入参数能直接改变父组件上的father值,v-model内部原理是怎么样的?
这是在input标签上使用v-model
<input v-model="father">
等价于
<input v-bind:value="father" v-on:input="father = $event.target.value" >
我写的demo用这个原理解释不通吧,此时更像是
<custom-input v-bind:value="father" v-on:input="father = 子组件传的参数" ></custom-input>
触发input事件,
cusomter-input
监听了input事件,$event.target
就是cusomter-input
组件实例,value
就是a
,father
被更新