【Vue3】动态组件的使用

简言

记录下动态组件的使用。
使用场景:多个组件需要来回切换使用时,可以考虑使用动态组件。

<component> 元素

component元素一个用于渲染动态组件或元素的“元组件”。
他有一个必需的属性is,is有以下特点:

  • 当 is 是字符串,它既可以是 HTML 标签名也可以是组件的注册名。
  • 或者,is 也可以直接绑定到组件的定义(组件导入对象)。

要渲染的实际组件由 is prop 决定。

按注册名渲染组件 (选项式 API):

<script>
import Foo from './Foo.vue'
import Bar from './Bar.vue'

export default {
  components: { Foo, Bar },
  data() {
    return {
      view: 'Foo'
    }
  }
}
</script>

<template>
  <component :is="view" />
</template>

按定义渲染组件 (<script setup> 组合式 API):

<script setup>
import Foo from './Foo.vue'
import Bar from './Bar.vue'
</script>

<template>
  <component :is="Math.random() > 0.5 ? Foo : Bar" />
</template>

渲染 HTML 元素:

<component :is="href ? 'a' : 'span'"></component>

除了is属性之外,它还接收其他属性,他将会传递到要渲染的组件中:

<component :is="RowCom" title="的22" content="你好2222">
        <template #name>
          <div>这是插槽name</div>
        </template>
      </component>
 <script setup>
	import RowCom from "@/components/row/rowCom.vue";

</script>

搭配KeepAlive

当使用 <component :is=“…”> 来在多个组件间作切换时,被切换掉的组件会被卸载。

相当于v-if …

我们可以通过 <KeepAlive> 组件强制被切换掉的组件仍然保持“存活”的状态。这样被切换后的组件仍然保存激活时的状态。

<template>
  <div class="index">
    <h1>动态组件is</h1>
    <ol>
      <div>one</div>
      <li>123</li>
      <li is="vue:row-com" title="的2" content="你好2" />
    </ol>
    <a-button @click="flag = !flag">切换</a-button>
    <keep-alive>
      <component
        :is="flag ? RowCom1 : RowCom2"
        v-bind="
          flag
            ? { title: 'rowcom1', content: '你好2222' }
            : { title: 'rowcom2', content: '你好22223' }
        "
      >
        <template #name>
          <div>这是插槽name</div>
        </template>
      </component>
    </keep-alive>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import RowCom1 from "@/components/row/rowCom.vue";
import RowCom2 from "@/components/row/rowCom2.vue";

const flag = ref(true);
</script>
<style lang="scss" scoped></style>

在这里插入图片描述

is

当 is attribute 用于原生 HTML 元素时。
你可能需要 Vue 用其组件来替换原生元素,可以在 is attribute 的值中加上 vue: 前缀,这样 Vue 就会把该元素渲染为 Vue 组件:

<table>
  <tr is="vue:my-row-component"></tr>
</table>

像这样他会将my-row-component组件替换tr元素。

不加vue:会认为is是一个普通的属性,

若加了vue:而没找到这个组件,则会解析为自定义元素。

<table>
      <tr is="vue:row-com12">
        <div>12321年少的</div>
      </tr>
    </table>

在这里插入图片描述

结语

结束了。

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZSK6

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值