先看官网说明:
<!-- 组件会在 `currentTabComponent` 改变时改变 -->
<component v-bind:is="currentTabComponent"></component>
在上述示例中,currentTabComponent 可以包括
- 已注册组件的名字,
- 或 一个组件的选项对象
vue3.3之后可以通过 defineOptions() 配置
<script setup lang="ts">defineOptions({name: 'Login'})
</script>
使用名字的我还没试,完了大家可以试试,我们说一下不使用名字的。vue2中之所以可以使用字符串形式,是因为我们我们在组件中写了name属性的。若没写name属性如何做?
<template><div class="auto-wrap"><div class="tabs-wrap"><divv-for="item in tabList":key="item":class="{ 'active-tabs': curComponentName == item.componentName }"class="tabs"@click="handleClickTab (item)">{{ item }}</div></div><component :is="curComponent" class="content"></component></div>
</template><script setup lang="ts">
import { markRaw, onMounted, ref, watch} from 'vue'
import passwordLogin from './passwordLogin.vue'
import phoneLogin from './phoneLogin.vue'const curComponent = ref(markRaw(passwordLogin))
const curComponentName = ref('passwordLogin')
// 定义对象存储组件实例
const compList = ref({passwordLogin:markRaw(passwordLogin),phoneLogin:markRaw(phoneLogin)
})
const tabList = ref([{name: '账号密码登录',componentName: 'passwordLogin'},{name: "手机快捷登录",componentName: "phoneLogin"}
])
const handleClickTab = (item) => {curComponent.value = compList.value[item.componentName]curComponentName.value = item.componentName
}
</script>
<style lang="scss" scoped>
.auto-wrap {background: #fff;display: flex;.tabs-wrap {width: 100px;height: 50px;line-height: 50px;.tabs {border: 1px solid #eee;padding: 3px;text-align: center;}.active-tabs {color: red;}}.content {padding: 12px;}
}
</style>