Vue3动态组件component详解

# Vue3动态组件component详解

动态组件component是Vue中非常实用的一个功能,它可以根据条件动态切换不同的组件。在Vue3中使用方法和Vue2基本一致。本文将详细介绍其用法。

## 基本用法使用

component组件时需要给它传入一个is属性,is绑定的是一个组件的名称:

<component :is="currentComponent"></component><component :is="currentComponent"></component>

然后通过改变currentComponent的值来动态修改需要渲染的组件:

import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue' 

export default {
  data() {
    return {
      currentComponent: 'ComponentA'
    }
  },
  components: {
    ComponentA,
    ComponentB 
  }
}

这样就可以通过修改currentComponent的值,来动态切换ComponentA和ComponentB了。我们也可以根据条件绑定不同的组件:

<component :is="type === 'A' ? 'ComponentA' : 'ComponentB'"></component> 

需要注意的是,对于动态组件,Vue会在组件切换时销毁前一个组件实例并创建新实例。所以切换动态组件时不会保留组件的状态。

## 组件缓存

如果需要缓存组件实例,可以使用`<KeepAlive>`组件包裹动态组件:

<KeepAlive>
  <component :is="currentComponent"></component>
</KeepAlive>

这样在切换组件时会进行复用,避免重复渲染。## 传递数据和监听生命周期可以通过props给动态组件传递数据:

<component :is="currentComponent" :item="item"></component> 

可以通过@hook来监听动态组件的生命周期钩子:

<component
  :is="currentComponent" 
  @hook:created="handleCreated"
  @hook:mounted="handleMounted"
></component>

动态组件也可以使用v-model进行数据同步。

## 完整示例

<template>
  <div>
    <button @click="currentView = 'A'">Show A</button>
    <button @click="currentView = 'B'">Show B</button>

    <component 
      :is="currentView"
      :item="item"
      @hook:mounted="handleMounted"
      v-model="data"
    />
  </div>
</template>


<script>
import { ref, defineComponent } from 'vue'
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'

export default defineComponent({
  components: {
    ComponentA,
    ComponentB
  },
  
  setup() {
    const currentView = ref('ComponentA')
    const item = ref({/*...*/})
    const data = ref(null)

    const handleMounted = () => {
      console.log('mounted') 
    }

    return {
      currentView,
      item,
      data,
      handleMounted
    }
  }
})
</script>

这样就展示了一个动态组件的完整用法,可以方便地在不同组件间进行切换并传递数据。动态组件非常适合需要根据不同条件展示不同内容的场景,掌握它可以更灵活地构建组件。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值