app.vue
<div id="app">
<my-component v-model="msg"></my-component>
msg: {{msg}}
<my-counter v-model="num"></my-counter>
num: {{num}}
</div>
my-component.vue
<template>
<div>
<input type="text" :value="currentValue" @input="handleInput"/>
</div>
</template>
<script>
export default {
data() {}
computed:{
currentValue () {
return this.value
}
},
props: ['value'], //接收一个 value prop
methods: {
handleInput(event) {
var value = event.target.value;
this.$emit('input', value); //触发 input 事件,并传入新值
}
}
});
</script>