MST

星途 面试题库

面试题:Vue中如何使用Composition API结合v - model指令实现双向绑定增强

在Vue项目中,通常使用v - model指令进行双向绑定。请阐述如何利用Composition API来增强v - model的功能,例如在一个自定义组件中,使用Composition API优化双向绑定的数据处理逻辑,给出实现思路和关键代码片段。
24.2万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 在自定义组件中,使用definePropsdefineEmits来声明接收的属性和触发的事件。
  2. 使用ref来创建响应式数据,用于存储v-model绑定的值。
  3. 监听update:modelValue事件,当外部数据更新时同步更新组件内的ref数据。
  4. 当组件内数据变化时,通过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>