Vue3 组合式 API 实现双向同步 Input 组件
在 Vue3 中,可以使用组合式 API 来创建组件。以下是一个使用组合式 API 的 Input 组件,它实现了双向同步功能:
<template>
<input :value='value' @input='updateValue($event.target.value)'>
</template>
<script>
import { defineComponent, ref, watch } from 'vue';
export default defineComponent({
props: {
modelValue: {
type: String,
default: ''
}
},
emits: ['update:modelValue'],
setup(props, { emit }) {
const value = ref(props.modelValue);
watch(() => props.modelValue, (newValue) => {
value.value = newValue;
});
function updateValue(newValue) {
value.value = newValue;
emit('update:modelValue', newValue);
}
return {
value,
updateValue
};
}
});
</script>
在这个组件中,我们定义了一个 props `modelValue`,用于接收外部传入的值。同时,我们也定义了一个事件 `update:modelValue`,用于向外部传递更新后的值。
在 `setup` 函数中,我们使用 `ref` 函数来创建一个响应式变量 `value`,并将 `props.modelValue` 的值赋给它。然后,我们使用 `watch` 函数来监听 `props.modelValue` 的变化,并将它更新到 `value` 中。最后,我们定义了一个 `updateValue` 函数,用于更新 `value` 的值,并将更新后的值通过 `emit` 函数传递给外部组件。
在模板中,我们使用 `v-bind:value` 指令来将 `value` 的值绑定到 `input` 元素的 `value` 属性上。然后,我们使用 `v-on:input` 指令来监听 `input` 元素的 `input` 事件,并调用 `updateValue` 函数来更新 `value` 的值。这样就完成了双向同步的功能。
原文地址: https://www.cveoy.top/t/topic/nmqu 著作权归作者所有。请勿转载和采集!