计数器组件上的 v 模型
这里 counter 是由 demo 访问的子组件,demo 是使用 v-model 的父组件。
// child component
Vue.component('counter', {
template: `<div><button @click='add'>+1</button>
<button @click='sub'>-1</button>
<div>this is inside the child component: {{ result }}</div></div>`,
data () {
return {
result: 0
}
},
props: ['value'],
methods: {
emitResult () {
this.$emit('input', this.result)
},
add () {
this.result += 1
this.emitResult()
},
sub () {
this.result -= 1
this.emitResult()
}
}
})
每次调用 sub() 或 add() 方法时,这个子组件将发出 result。
// parent component
new Vue({
el: '#demo',
data () {
return {
resultFromChild: null
}
}
})
// parent template
<div id='demo'>
<counter v-model='resultFromChild'></counter>
This is in parent component {{ resultFromChild }}
</div>
由于 v-model 出现在子组件上,同时发送名为 value 的道具,counter 上有一个输入事件,它将提供子组件的值。