<input v-model="something">
v-model指令实际上是下面的语法糖包装而成:html
<input :value="something" @:input="something = $event.target.value">
在一个组件上使用 v-model 时,会简化为:vue
<custom-input :value="something" @input="value => { something = value }"> </custom-input>
所以,对于一个带有 v-model
的组件,它应该以下:ide
value
propinput
事件,并传入新值利用 $emit 触发 input 事件:ui
this.$emit('input', value);
组件1:this
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:spa
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 事件,并传入新值 } } } });
查看在线例子.net