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);
        }
       })
    }
相关推荐
ZC跨境爬虫15 分钟前
跟着 MDN 学 HTML day_52:(深入 XPathExpression 接口)
开发语言·前端·javascript·ui·html·音视频
不会写DN27 分钟前
通过白名单解决 pnpm i 报错 Ignored build scripts
javascript·面试·npm
UXbot28 分钟前
AI 原型工具零设计基础操作指南与功能解析(2026)
前端·ui·产品经理·原型模式·web app
yuzhiboyouye1 小时前
VO一般java后端怎么转换成前端想要的数据
java·前端·状态模式
一 乐1 小时前
学院教学工作量统计|基于java+ vue学院教学工作量统计管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·学院教学工作量统计系统
小脑斧1231 小时前
从范式重构到工程落地:OpenTiny NEXT 引领前端智能化新范式
前端·hermesagent·opentiny next
小江的记录本1 小时前
【AI大模型选型指南】《2026年5月(最新版)国内外主流AI大模型选型指南》(企业版)
前端·人工智能·后端·ai作画·aigc·ai编程·ai写作
幽络源小助理2 小时前
最新轻量美化表白墙系统源码v2.0_带后台版_附搭建教程
前端·开源·源码·php源码
qq_381338502 小时前
前端状态管理新范式:Zustand、Jotai 与 Preact Signals 深度对比
前端·arcgis
布局呆星2 小时前
Vue Router 笔记(二):正则路由、组件通信与动态路由
前端·javascript·vue.js