当前位置: 首页 > article >正文

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>

关键点

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

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

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

原文地址:https://blog.csdn.net/weixin_74457498/article/details/146361440
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.kler.cn/a/592916.html

相关文章:

  • CSGHub开源版本v1.5.0更新
  • Leetcode-100 回溯法-子集
  • 单元测试、系统测试、集成测试、回归测试的步骤、优点、缺点、注意点梳理说明
  • 【深度学习量化交易18】盘前盘后回调机制设计与实现——基于miniQMT的量化交易回测系统开发实记
  • Leetcode 刷题笔记1 单调栈part01
  • 瑞幸需要宇树科技
  • 使用hel-micro微服务实现在jsp项目中引入react组件
  • Jenkins自动化部署pigx项目的实践总结
  • DLMS电能表通讯协议学习笔记
  • 2025三掌柜赠书活动第八期:预训练语言模型:方法、实践与应用
  • 联核科技AGV无人叉车有哪些常见的安全防护措施?
  • Flutter小白零基础入门到高级项目实战全集
  • 解决uni-app授权弹框华为审核拒绝
  • vscode+wsl2+bear+clangd配置教程
  • 【Spark】查询优化中分区(Partitioning)和分桶(Bucketing)是什么关系?什么时候应当分区,什么时候应当分桶?
  • 【sgAutocomplete_v2】自定义组件:基于elementUI的el-input组件开发的搜索输入框(支持本地保存历史搜索关键词、后台获取匹配项)
  • flutter 专题 九十 四 Flutter开发之基础知识
  • xss注入实验(xss-lab)
  • 4.1-1 IS-NET-Pro视频转图片的插件
  • 在ASP.NET Core中使用NLog:配置与性能优化指南