<div id="app">
<my-component v-model="msg"></my-component>
msg: {{msg}}
<my-counter v-model="num"></my-counter>
num: {{num}}
</div>
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 事件,并传入新值
}
}
});
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 事件,并传入新值
}
}
}
});
new Vue({
el: '#app',
data: {
msg: 'hello world',
num: 0
}
})
网友评论