Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue3获取组件实例

作者:故事没有她   发布日期:2025-10-08   浏览:92

// 在 Vue 3 中获取组件实例的方法可以通过 ref 和 getCurrentInstance 来实现。下面是具体的示例代码:

// 示例 1: 使用 ref 获取子组件实例
<template>
  <ChildComponent ref="childComponent" />
  <button @click="callChildMethod">Call Child Method</button>
</template>

<script>
import { ref, onMounted } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  setup() {
    const childComponent = ref(null);

    const callChildMethod = () => {
      if (childComponent.value) {
        childComponent.value.childMethod();
      }
    };

    return {
      childComponent,
      callChildMethod
    };
  }
};
</script>

// 示例 2: 使用 getCurrentInstance 获取当前组件实例
<script>
import { getCurrentInstance } from 'vue';

export default {
  setup() {
    const instance = getCurrentInstance();

    console.log(instance); // 输出当前组件实例

    return {};
  }
};
</script>

// 解释说明:
// 1. 在示例 1 中,我们使用 `ref` 来引用子组件实例,并通过 `childComponent.value` 来调用子组件的方法。
// 2. 在示例 2 中,我们使用 `getCurrentInstance` 来获取当前组件的实例,这在某些情况下(如需要访问组件内部属性或方法时)非常有用。

上一篇:vue render函数

下一篇:vue definecomponent

大家都在看

vue js for循环

vue.config.js 配置

vue.config.js configu

node.js vue

vue3组件传值的方式

vue 图表组件

vue3+vite+ts

vue3watch监听多个变量

vue查看版本

vue3 reactive对象重新赋值

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站