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);
        }
       })
    }
相关推荐
Blanche1500几秒前
Webpack 构建流程解析
javascript·面试
粥里有勺糖1 分钟前
体验一下最近比较🔥的闪卡SKILL
前端·github
flash俊杰1 分钟前
WebGL 实时合成管线:纹理、Shader 滤镜链与离屏渲染调度
前端
前端snow1 分钟前
ai agent --- LangSmith 全链路观测
前端
Csvn2 分钟前
Hooks 原理:把"每次重跑的函数"变成"有记忆的组件"
前端
计算机魔术师2 分钟前
用AI拒批老人看病?美国这个试点项目的激励机制出了大问题
前端
风骏时光牛马2 分钟前
AI服务线上响应异常故障
前端
IT_陈寒2 分钟前
JavaScript的this指向问题又让我加了个班
前端·人工智能·后端
PC2005_cloud2 分钟前
Nginx 学习笔记:Server 块配置详解,域名路由与多站点部署实战
前端·后端
YIAN2 分钟前
LangChain.js 对话记忆体系(一):内存存储与文件持久化,让 AI 拥有对话记忆
前端·后端·langchain