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);
        }
       })
    }
相关推荐
前端甜糖10 分钟前
记录We码开发者工具的一个bug
前端·javascript
程序员黑豆19 分钟前
鸿蒙应用开发教程:以红绿灯切换为例,掌握条件渲染的核心用法
前端·harmonyos
猫32827 分钟前
echarts 日常问题解决
前端·javascript·echarts
新中地GIS开发老师30 分钟前
地信职业百科④:GIS开发工程师
前端·数据库·gis·webgis·三维gis开发
我是大卫39 分钟前
【图】React源码解析-从数据结构、调度器、源码设计模式到状态计算引擎,深挖useReducer原理
前端·react.js·源码
willes1 小时前
列表中的倒计时组件
前端
LVZ1 小时前
用了半年 AI 写代码,最烦的不是代码,是环境
前端·后端·开源
polaris_tl1 小时前
一行 `compress: false`,为什么让 SSE 首包恢复实时返回
前端
海边的云1 小时前
别再让 AI 瞎改代码:一套让大模型「收敛」的前端专家 Skill》
前端
kisshyshy1 小时前
给端侧大模型装上“发动机”:React 合成事件 + 进度条组件全解
前端·react.js·node.js