Vue3 中setup模式下component标签 is属性动态绑定组件空白显示问题

225 篇文章 1 订阅
199 篇文章 4 订阅

先看官网说明:

<!-- 组件会在 `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">
      <div
        v-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>


  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值