v-model语法糖的实现
1 定义子组件
<template>
<div>
<span>
<input
ref="input"
:value="value"
@input="$emit('input', $event.target.value)"
/>
</span>
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
default: "",
},
},
};
</script>
2 在父组件中使用子组件
<template>
<div>
<!-- v-model语法糖的实现 -->
<my-input v-model="price" />
<!-- 不使用v-model -->
<my-input :value="price" @input="inputChange" />
<h2>{{ price }}</h2>
</div>
</template>
<script>
import MyInput from "./components/MyInput.vue";
export default {
name: "Test0726",
components: {
MyInput,
},
data() {
return {
price: "",
};
},
methods: {
inputChange(e) {
this.price = e;
},
},
};
</script>
在控制台测试如下: