Vue3中ts父子组件传值

父组件代码

在父组件中正确地将 activeType 绑定到子组件的 v-model 上。

<template>
  <div>
    <!-- 将 activeType 绑定到子组件的 v-model -->
    <ChildComponent v-model:activeType="activeType" />
    <p>父组件中的 activeType: {{ activeType }}</p>
  </div>
</template>

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

// 父组件中的 activeType,绑定到子组件的 v-model
const activeType = ref<string>('');

// 监听 activeType 的变化
watch(activeType, (newVal) => {
  console.log('父组件中的 activeType 更新为:', newVal);
});
</script>

子组件代码

<template>
  <div>
    <!-- 假设你有一个输入框来修改 activeType -->
    <input v-model="activeType" />
  </div>
</template>

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

// 定义 props,modelValue 类型是 string
const props = defineProps<{
  modelValue: string;
}>();

// 定义 emit 类型,触发 update:modelValue 事件时传递一个 string 类型的值
const emit = defineEmits<{
  (event: 'update:modelValue', value: string): void;
}>();

// 初始化 activeType 为 props.modelValue
const activeType = ref(props.modelValue);

// 监听 activeType 的变化,及时通知父组件更新值
watch(activeType, (newVal) => {
  emit('update:modelValue', newVal);
});
</script>

关键点

  1. v-model 绑定:确保在父组件中使用 v-model 将 activeType 绑定到子组件。

  2. emit 触发:子组件通过 emit('update:modelValue', newVal) 将变化传递给父组件。

  3. watch 监听:父组件可以通过 watch 监听 activeType 的变化,确保值更新时能够及时响应。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值