首页 前端知识 Vue3动态组件component详解

Vue3动态组件component详解

2024-02-03 12:02:29 前端知识 前端哥 224 8 我要收藏

# 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>

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

转载请注明出处或者链接地址:https://www.qianduange.cn//article/1211.html
标签
评论
会员中心 联系我 留言建议 回顶部
复制成功!