// 在 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函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站