vue3子组件与父组件双向数据绑定

<template>
  <div>
    <el-input
      v-model="input1"
      placeholder="输入框1"
      @input="handleInput"
    />
    <el-input
      v-model="input2"
      placeholder="输入框2"
      @input="handleInput"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';

// 定义 props(接收父组件传递的初始值)
const props = defineProps({
  input1: {
    type: String,
    default: '',
  },
  input2: {
    type: String,
    default: '',
  },
});

// 定义 emits(向父组件发送事件)
const emit = defineEmits(['update:input1', 'update:input2']);

// 子组件的输入框数据
const input1 = ref(props.input1);
const input2 = ref(props.input2);

// 监听输入框数据变化
const handleInput = () => {
  emit('update:input1', input1.value);
  emit('update:input2', input2.value);
};

// 监听 props 的变化,更新子组件数据
watch(
  () => props.input1,
  (newValue) => {
    input1.value = newValue;
  }
);
watch(
  () => props.input2,
  (newValue) => {
    input2.value = newValue;
  }
);
</script>

 

 

<template>
  <div>
    <h1>父组件</h1>
    <SearchBar
      v-model:input1="formData.input1"
      v-model:input2="formData.input2"
      @search="onSearch"
    />
    <p>输入框1的值:{{ formData.input1 }}</p>
    <p>输入框2的值:{{ formData.input2 }}</p>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import SearchBar from '@/components/SearchBar.vue';

// 父组件的数据
const formData = ref({
  input1: '',
  input2: '',
});

// 搜索事件
const onSearch = (value: any) => {
  console.log('搜索内容:', value);
};
</script>

 

posted @ 2024-12-30 10:17  Webwhl  阅读(259)  评论(0)    收藏  举报