vue3中子组件获取父组件的name,父组件不做修改动作

在 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 函数或者

你可能感兴趣的:(vue,web前端,vue.js,javascript,前端)