vue3 $refs
时间: 2023-10-10 15:12:01 浏览: 92
Vue 3 introduces a new way to access child components using the `$refs` property. The `$refs` property is a reactive object that provides direct access to DOM elements or child components within a parent component.
To use `$refs`, you need to assign a unique `ref` attribute to the desired element or component in the template. For example, in your parent component's template, you can define a ref for a child component like this:
```html
<template>
<child-component ref="myChild"></child-component>
</template>
```
Now, you can access this child component using the `$refs` property in your parent component's methods, computed properties, or lifecycle hooks. For example:
```javascript
export default {
mounted() {
const childComponent = this.$refs.myChild;
// Access child component's methods or properties
childComponent.someMethod();
console.log(childComponent.someProperty);
},
}
```
Remember that `$refs` is not reactive; it won't update automatically if the referenced component changes. It is also important to note that `$refs` is only populated after the component has been rendered, so you should avoid accessing it during the `beforeMount` lifecycle hook.
I hope this helps! Let me know if you have any more questions.
阅读全文