下面以一个 input 组件实现的核心代码,介绍下 v-model
的应用。
<!--父组件-->
<template>
<base-input v-model="input"></base-input>
</template>
<script>
export default {
data() {
return {
input: ''
}
},
}
</script>
<!--子组件-->
<template>
<input type="text" :value="currentValue" @input="handleInput">
</template>
<script>
export default {
data() {
return {
currentValue: this.value === undefined || this.value === null ? ''
}
},
props: {
value: [String, Number],
},
methods: {
handleInput(event) {
const value = event.target.value;
this.$emit('input', value);
},
},
}
</script>