Vue3 调用子组件的方法和变量

1. 通过 ref 调用子组件的方法和变量

Vue 3 引入了 ref,你可以通过 ref 获取子组件实例,并调用其方法或访问其数据。

例子

子组件 (Child.vue)

复制代码
<template>
  <div>
    <p>{{ message }}</p>
    <button @click="updateMessage">Update Message</button>
  </div>
</template>

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

// 子组件的响应式数据
const message = ref<string>('Hello from child!');

// 子组件的方法
const updateMessage = () => {
  message.value = 'Message updated by child';
};
</script>

父组件 (Parent.vue)

复制代码
<template>
  <div>
    <!-- 通过 ref 引用子组件 -->
    <Child ref="childComponent" />
    <button @click="callChildMethod">Call Child Method</button>
    <p>Message from child: {{ childMessage }}</p>
  </div>
</template>

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

// 父组件引用子组件
const childComponent = ref<typeof Child | null>(null);
const childMessage = ref<string>('');

// 父组件调用子组件的方法
const callChildMethod = () => {
  if (childComponent.value) {
    // 调用子组件的方法
    childComponent.value.updateMessage();
    // 获取子组件的数据
    childMessage.value = childComponent.value.message;
  }
};
</script>

在这个例子中:

  • 在父组件中,我们使用 ref="childComponent" 来引用子组件实例。
  • childComponent.value.updateMessage() 调用子组件的 updateMessage 方法。
  • 子组件的 message 数据被更新后,父组件通过 childMessage 变量显示该值。

同样,这种方式可以调用子组件中的变量,这种方式,子组件变量改变时,父组件也会跟着改变

2、延伸

有一次,父组件里MessageItem是在li中循环使用的,想要调用子组件MessageItem里的方法,使用Ref.loadingShowFn(flag)并未取到值,打印发现,因为是循环使用,ref.value是一个多数组,需要遍历取值

复制代码
<li
          v-for="(item, index) in messages"
          :key="index"
          :id="item?.ID"
          ref="messageAimID"
        >
         
          <MessageItem
            @sendMoreJobMsg="sendMoreJobMsg"
          >
          </MessageItem>
        </li>

const loadingPost = (flag:boolean) => {
      mList.value.forEach(childRef => {
       if (childRef && childRef.loadingShowFn) {
        childRef.loadingShowFn(flag);
        }
       })
    }
相关推荐
掘金安东尼11 分钟前
前端周刊第421期(2025年7月1日–7月6日)
前端·面试·github
摸鱼仙人~14 分钟前
深入理解 classnames:React 动态类名管理的最佳实践
前端·react.js·前端框架
未来之窗软件服务16 分钟前
chrome webdrive异常处理-session not created falled opening key——仙盟创梦IDE
前端·人工智能·chrome·仙盟创梦ide·东方仙盟·数据调式
kymjs张涛16 分钟前
零一开源|前沿技术周报 #6
前端·ios·harmonyos
玲小珑20 分钟前
Next.js 教程系列(十)getStaticPaths 与动态路由的静态生成
前端·next.js
天天鸭26 分钟前
写个vite插件自动处理系统权限,降低99%重复工作
前端·javascript·vite
蓝婷儿30 分钟前
每天一个前端小知识 Day 23 - PWA 渐进式 Web 应用开发
前端
无奈何杨40 分钟前
CoolGuard风控中新增移动距离和移动速度指标
前端·后端
恋猫de小郭1 小时前
Google I/O Extended :2025 Flutter 的现状与未来
android·前端·flutter
江城开朗的豌豆1 小时前
Vue-router方法大全:让页面跳转随心所欲!
前端·javascript·vue.js