vue3 封装一个子组件动态访问
时间: 2023-10-31 11:58:26 浏览: 42
在Vue3中,可以使用`ref`和`setup`来封装一个子组件,并动态访问它。下面是一个示例代码:
```vue
<template>
<div>
<button @click="showChildComponent = !showChildComponent">
{{ showChildComponent ? '隐藏' : '显示' }}子组件
</button>
<hr>
<div v-if="showChildComponent">
<child-component ref="childComponent" />
</div>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
import { ref } from 'vue'
export default {
components: { ChildComponent },
setup() {
const showChildComponent = ref(false)
return {
showChildComponent
}
},
methods: {
accessChildComponent() {
if (this.showChildComponent) {
console.log(this.$refs.childComponent)
// 调用子组件方法
this.$refs.childComponent.childMethod()
}
}
}
}
</script>
```
在上述代码中,我们使用`ref`来创建一个引用到子组件。然后在`setup`函数中,返回这个引用对象。在父组件的方法中,我们可以通过`this.$refs.childComponent`来访问子组件,并调用子组件的方法。