Vue3中ts父子组件传值
父组件代码
在父组件中正确地将 activeType
绑定到子组件的 v-model
上。
<template>
<div>
<!-- 将 activeType 绑定到子组件的 v-model -->
<ChildComponent v-model="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>
关键点
-
v-model
绑定:确保在父组件中使用v-model
将activeType
绑定到子组件。 -
emit
触发:子组件通过emit('update:modelValue', newVal)
将变化传递给父组件。 -
watch
监听:父组件可以通过watch
监听activeType
的变化,确保值更新时能够及时响应。
原文地址:https://blog.csdn.net/weixin_74457498/article/details/146361440
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.kler.cn/a/592916.html 如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.kler.cn/a/592916.html 如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!