Vue3 内置组件之component
概述
<component>
组件提供了动态组件加载功能,它可以在内置组件Component占位点上将自定义组件进行指定目标的渲染。比如页面中常见的Tabs选项卡效果就可以利用动态组件加载功能轻松实现。
使用
定义三个组件:
Comp1.vue:
<template>
<h2>组件一</h2>
<p>这是一些内容1111111</p>
</template>
Comp2.vue:
<template>
<h2>组件二</h2>
<p>这是一些内容222222</p>
</template>
Comp3.vue:
<template>
<h2>组件三</h2>
<p>这是一些内容33333333</p>
</template>
使用component组件:
<script setup>
import {markRaw, ref} from "vue";
import Comp1 from "./components/Comp1.vue";
import Comp2 from "./components/Comp2.vue";
import Comp3 from "./components/Comp3.vue";
// 标记为原始对象,表示内部不能被修改
const tab = ref(markRaw(Comp1));
// 切换组件
function switchTab(comp) {
tab.value = markRaw(comp);
}
// 默认显示
switchTab(Comp1);
</script>
<template>
<h1>内置组件之component</h1>
<button @click="switchTab(Comp1)">切换组件一</button>
<button @click="switchTab(Comp2)">切换组件二</button>
<button @click="switchTab(Comp3)">切换组件三</button>
<component :is="tab"></component>
</template>
效果: