vue3 ref获取组件实例详细图文教程
作者:鲸落_Libra
在Vue3中可以使用ref函数来创建一个响应式的变量,通过将ref函数应用于一个组件实例,我们可以获取到该组件的实例对象,这篇文章主要给大家介绍了关于vue3 ref获取组件实例的详细图文教程,需要的朋友可以参考下
1.ref获取组件实例时前面不要写冒号
需要注意的是通过ref拿到组件的属性或方法必须是子组件return出来的
具体如下
<!--tempaleteb标签的内容-->
<!-- 注意:ref前面不能有冒号 -->
? ? <h1 ref="title">我是标题</h1>
? ? <child ref="child"></child>? ? ? ? ? ? ?
//setup函数内的内容
?// 通过ref获取组件实例
? ? const child = ref(null)
? ? const title = ref(null)
//挂载完成后获取实例
? ? onMounted(() => {
? ? ? ? console.log(child.value)
? ? ? ? console.log(title.value)
? ? ? ? child.value.hh()
? ? })效果图如下

2.组件介绍
Fragment 组件
在 vue2.x 中组件模板必须要一个根标签;但是在 vue3.x 中不再需要一个根标签,它会自 动创建一个 Fragment
<template>
<div>我是描述</div>
<h3>我是标题</h3>
</template>
<script>
export default {};
</script>
<style></style>3.Suspense 组件
加载异步组件的时候,渲染一些其他内容
App.vue
<template>
? <div class="app">
? ? <Suspense>
? ? ? <template v-slot:default>
? ? ? ? <Child />
? ? ? </template>
? ? ? <template v-slot:fallback>
? ? ? ? <h1>加载中...</h1>
? ? ? </template>
? ? </Suspense>
? </div>
</template>
<script>
// import Child from './Child.vue'; // 程序开始就会打包编译
// 导入defineAsyncComponent 方法 定义异步加载组件
import { defineAsyncComponent } from "vue";
const Child = defineAsyncComponent(() => import("./Child.vue"));
export default {
? components: {
? ? Child,
? },
};
</script>
<style scoped>
.app {
? background-color: #eee;
? padding: 30px;
}
</style>child.vue
<template>
<div class="child">我是子组件</div>
</template>
<script>
export default {};
</script>
<style scoped>
.child {
border: 2px solid red;
margin: 20px;
padding: 20px;
}
</style>4.Teleport 组件
作用: 将指定 DOM 内容移动到指定的某个节点里面(可以理解为将组件挂载到指定节点上面) 使用场景: 弹框、播放器组件的定位
dialog.vue
<template>
<div class="dialog">我是弹框</div>
</template>
<script>
export default {};
</script>
<style scoped>
.dialog {
width: 300px;
height: 300px;
padding: 30px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}
</style>app.vue
<template>
<div class="app">
<h3>我是标题</h3>
<h1>我是一级标题</h1>
<div id="test">
<!-- to属性的值为选择器,表示放在哪个节点下面 -->
<teleport to="body">
<Dialog />
</teleport>
</div>
</div>
</template>
<script>
import Dialog from "./Dialog.vue";
export default {
components: {
Dialog,
},
};
</script>
<style scoped>
.app {
background-color: #eee;
padding: 30px;
}
</style>运行结果

总结
到此这篇关于vue3 ref获取组件实例的文章就介绍到这了,更多相关vue3 ref获取组件实例内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
