計數器元件上的 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
上有一個輸入事件,它將提供子元件的值。