实现思路
- 在自定义组件中,使用
defineProps
和defineEmits
来声明接收的属性和触发的事件。
- 使用
ref
来创建响应式数据,用于存储v-model
绑定的值。
- 监听
update:modelValue
事件,当外部数据更新时同步更新组件内的ref
数据。
- 当组件内数据变化时,通过
emit
触发update:modelValue
事件通知父组件更新。
关键代码片段
<template>
<input :value="inputValue" @input="handleInput">
</template>
<script setup>
import { ref } from 'vue';
const props = defineProps(['modelValue']);
const emit = defineEmits(['update:modelValue']);
const inputValue = ref(props.modelValue);
const handleInput = (e) => {
inputValue.value = e.target.value;
emit('update:modelValue', inputValue.value);
};
watch(() => props.modelValue, (newValue) => {
inputValue.value = newValue;
});
</script>