Vue3如何获取组件实例
时间: 2023-09-10 14:13:11 浏览: 168
在 Vue3 中获取组件实例有两种方法:
1. 使用 `ref` 引用组件,并通过 `value` 属性获取实例:
```html
<template>
<div>
<MyComponent ref="myComponentRef" />
</div>
</template>
<script>
import MyComponent from './MyComponent.vue';
export default {
components: {
MyComponent
},
mounted() {
const myComponentInstance = this.$refs.myComponentRef.value;
console.log(myComponentInstance);
}
}
</script>
```
2. 使用 `setup` 函数中的 `getCurrentInstance` 方法获取当前实例,并通过 `refs` 属性获取组件实例:
```html
<template>
<div>
<MyComponent />
</div>
</template>
<script>
import { getCurrentInstance } from 'vue';
import MyComponent from './MyComponent.vue';
export default {
components: {
MyComponent
},
setup() {
const instance = getCurrentInstance();
const myComponentRef = instance.refs.myComponentRef;
console.log(myComponentRef.value);
}
}
</script>
```
注意:在 Vue3 中,组件实例可以通过 `refs` 属性获取,而不是像 Vue2 中通过 `$refs` 属性获取。
阅读全文
相关推荐


















