当前位置:   article > 正文

Vue3动态组件component详解_vue3 component

vue3 component

# Vue3动态组件component详解

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

## 基本用法使用

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

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

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

  1. import ComponentA from './ComponentA.vue'
  2. import ComponentB from './ComponentB.vue'
  3. export default {
  4. data() {
  5. return {
  6. currentComponent: 'ComponentA'
  7. }
  8. },
  9. components: {
  10. ComponentA,
  11. ComponentB
  12. }
  13. }

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

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

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

## 组件缓存

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

  1. <KeepAlive>
  2. <component :is="currentComponent"></component>
  3. </KeepAlive>

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

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

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

  1. <component
  2. :is="currentComponent"
  3. @hook:created="handleCreated"
  4. @hook:mounted="handleMounted"
  5. ></component>

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

## 完整示例

  1. <template>
  2. <div>
  3. <button @click="currentView = 'A'">Show A</button>
  4. <button @click="currentView = 'B'">Show B</button>
  5. <component
  6. :is="currentView"
  7. :item="item"
  8. @hook:mounted="handleMounted"
  9. v-model="data"
  10. />
  11. </div>
  12. </template>
  13. <script>
  14. import { ref, defineComponent } from 'vue'
  15. import ComponentA from './ComponentA.vue'
  16. import ComponentB from './ComponentB.vue'
  17. export default defineComponent({
  18. components: {
  19. ComponentA,
  20. ComponentB
  21. },
  22. setup() {
  23. const currentView = ref('ComponentA')
  24. const item = ref({/*...*/})
  25. const data = ref(null)
  26. const handleMounted = () => {
  27. console.log('mounted')
  28. }
  29. return {
  30. currentView,
  31. item,
  32. data,
  33. handleMounted
  34. }
  35. }
  36. })
  37. </script>

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/215430
推荐阅读
相关标签
  

闽ICP备14008679号