<input v-model="something">
v-model指令其實是下面的語法糖包裝而成:
<input :value="something" @:input="something = $event.target.value">
在一個組件上使用 v-model 時,會簡化為:
<custom-input :value="something" @input="value => { something = value }"> </custom-input>
因此,對於一個帶有 v-model 的組件,它應該如下:
- 接收一個
valueprop - 觸發
input事件,並傳入新值
利用 $emit 觸發 input 事件:
this.$emit('input', value);
組件1:
Vue.component('my-component', {
template: `<div>
<input type="text" :value="currentValue" @input="handleInput"/>
</div>`,
computed:{
currentValue:function () {
return this.value
}
},
props: ['value'], //接收一個 value prop
methods: {
handleInput(event) {
var value = event.target.value;
this.$emit('input', value); //觸發 input 事件,並傳入新值
}
}
});
上面是將prop屬性綁定到data里,以便修改 prop 數據(Vue不允許直接修改prop屬性的值)#查看原理#
組件2:
Vue.component("my-counter", {
template: `<div>
<h1>{{value}}</h1>
<button @click="plus">+</button>
<button @click="minu">-</button>
</div>`,
props: {
value: Number //接收一個 value prop
},
data: function() {
return {
val: this.value
}
},
methods: {
plus() {
this.val = this.val + 1
this.$emit('input', this.val) //觸發 input 事件,並傳入新值
},
minu() {
if(this.val>0){
this.val = this.val-1
this.$emit('input', this.val) //觸發 input 事件,並傳入新值
}
}
}
});
查看在線例子
