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);
        }
       })
    }
相关推荐
tuokuac6 分钟前
nginx配置前端请求转发到指定的后端ip
前端·tcp/ip·nginx
程序员爱钓鱼9 分钟前
Go语言实战案例-开发一个Markdown转HTML工具
前端·后端·go
万少31 分钟前
鸿蒙创新赛 HarmonyOS 6.0.0(20) 关键特性汇总
前端
还有多远.1 小时前
jsBridge接入流程
前端·javascript·vue.js·react.js
蝶恋舞者1 小时前
web 网页数据传输处理过程
前端
非凡ghost1 小时前
FxSound:提升音频体验,让音乐更动听
前端·学习·音视频·生活·软件需求
w2sfot1 小时前
Passing Arguments as an Object in JavaScript
开发语言·javascript·ecmascript
烛阴1 小时前
【TS 设计模式完全指南】从零到一:掌握TypeScript建造者模式,让你的对象构建链式优雅
javascript·设计模式·typescript
吃饭最爱1 小时前
html的基础知识
前端·html
我没想到原来他们都是一堆坏人1 小时前
(未完待续...)如何编写一个用于构建python web项目镜像的dockerfile文件
java·前端·python