当前位置: 首页> 房产> 建筑 > 嵌入式软件开发哪家好_邯郸市网络公司_线上营销渠道有哪些_网站内部链接优化方法

嵌入式软件开发哪家好_邯郸市网络公司_线上营销渠道有哪些_网站内部链接优化方法

时间:2025/7/27 18:22:18来源:https://blog.csdn.net/a12336487213/article/details/146060806 浏览次数:0次
嵌入式软件开发哪家好_邯郸市网络公司_线上营销渠道有哪些_网站内部链接优化方法

在 Vue 3 中,子组件若要获取父组件的 name,且父组件不做额外操作,可以借助 getCurrentInstance 来实现。getCurrentInstance 方法能获取当前组件实例,进而访问其父组件实例及其属性。
示例代码
父组件(ParentComponent.vue)

<template><div><h1>这是父组件</h1><ChildComponent /></div>
</template><script setup>
import { defineComponent } from 'vue';
import ChildComponent from './ChildComponent.vue';// 定义父组件名称
defineComponent({name: 'ParentComponent'
});
</script>

子组件(ChildComponent.vue)

<template><div><h2>这是子组件</h2><p>父组件的名称是: {{ parentName }}</p></div>
</template><script setup>
import { getCurrentInstance } from 'vue';// 获取当前组件实例
const instance = getCurrentInstance();
// 获取父组件的 name
const parentName = instance?.parent?.type.__name;
</script>

代码解释
父组件:
运用 defineComponent 定义父组件,并且指定 name 为 ParentComponent。
在模板里引入并使用子组件 ChildComponent。
子组件:
借助 getCurrentInstance 获取当前组件实例。
通过 instance?.parent 访问父组件实例。
利用 instance?.parent?.type.__name 获取父组件的 name。
把获取到的父组件 name 展示在模板中。
注意事项
getCurrentInstance 仅能在 setup 函数或者 <script setup> 中使用。
由于 getCurrentInstance 可能返回 null,所以在访问父组件实例及其属性时,要使用可选链操作符 ?. 来避免出现空指针错误。
----来自豆包

关键字:嵌入式软件开发哪家好_邯郸市网络公司_线上营销渠道有哪些_网站内部链接优化方法

版权声明:

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

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

责任编辑: