当前位置: 首页> 汽车> 车展 > 应用app官方下载_免费网站域名_网络整合营销理论案例_百度竞价推广课程

应用app官方下载_免费网站域名_网络整合营销理论案例_百度竞价推广课程

时间:2025/7/9 4:11:03来源:https://blog.csdn.net/u010865136/article/details/144120348 浏览次数: 1次
应用app官方下载_免费网站域名_网络整合营销理论案例_百度竞价推广课程

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是一个多数组,需要遍历取值

<liv-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);}})}

关键字:应用app官方下载_免费网站域名_网络整合营销理论案例_百度竞价推广课程

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: