vue动态组件之:is在组件中的使用场景
作者:seekHelp
这篇文章主要介绍了vue动态组件之:is在组件中的使用场景,本文结合示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
vue动态组件之:is在组件中的使用
使用场景:
有些场景会需要在两个组件间来回切换,比如 Tab 界面:
我们可以通过 Vue 的<component> 元素和特殊的 is attribute 实现的:如
<!-- currentTab 改变时组件也改变 --> <component :is="currentTab"></component>
在上面的例子中,被传给:is的值可以是以下几种:
- 被注册的组件名
- 导入的组件对象
你也可以使用isattribute 来创建一般的 HTML 元素。
当使用 <component :is="...">来在多个组件间作切换时,被切换掉的组件会被卸载。我们可以通过 <KeepAlive> 组件强制被切换掉的组件仍然保持“存活”的状态。
vue3中的:is 动态组件
1、注意事项
1、在Vue2 的时候is是通过组件名称切换的,在Vue3 setup是通过组件实例切换的
2、如果直接把组件实例放到reactive中代理,vue会发出警告。告知我们可以通过shallowRef 或者 markRaw 跳过proxy 代理。因为组件实例进行响应式代理毫无意义,且浪费性能

2、:is 动态组件使用
子组件通过defineProps接受传参
<template>
<div class="content">
<div class="tabs" v-for="item in tabArr" :key="item.name" @click="tabChange(item.comName)">
{{ item.name }}
</div>
</div>
<component :is="currentCom"></component>
</template>
<script setup lang="ts">
import { ref, reactive, markRaw } from 'vue'
import A from './A.vue'
import B from './B.vue'
import C from './C.vue'
type Tab = {
name: string,
comName: any
}
// 从复杂数据类型中取出自己想要的几个属性
type Com = Pick<Tab, 'comName'>
const tabArr = reactive<Tab[]>([
{
name: 'A组件',
comName: markRaw(A)
},
{
name: 'B组件',
comName: markRaw(B)
},
{
name: 'C组件',
comName: markRaw(C)
},
])
const currentCom = ref<Com>(tabArr[0].comName)
const tabChange = (item: Com) => {
currentCom.value = item
}
</script>
<style>
.content {
display: flex;
padding: 20px;
height: 40px;
width: 100vw;
background: #f1f1f1;
}
.tabs {
width: 100px;
height: 40px;
background: #ffffff;
margin-right: 5px;
border: 1px solid #000;
}
</style>到此这篇关于vue - 动态组件(:is在组件中的使用)的文章就介绍到这了,更多相关vue动态组件:is内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
