Vue高级特性之动态组件

动态组件是指:在一个挂载点使用多个组件,并进行动态切换。

组件类型不确定,需要根据数据,动态渲染的场景下,我们会使用到动态组件。你看下面的新闻详情页,详情页里的组件类型不确定、需要渲染的组件数量也不确定,可能这个页面是图文结合的,另个页面是视频和文字结合的,这种场景就正中“动态组件”下怀了!

动态组件语法:

<component :is="component-name"></component>

示例代码:

<template>
  <div>

    <div v-for="item in newsList" :key="item.id">
      <component :is="item.type" />
    </div>

  </div>
</template>

<script>
import ImageComp from './components/image-comp.vue'
import VideoComp from './components/video-comp.vue'
import TextComp from './components/text-comp.vue'
export default {
  components: { ImageComp, VideoComp, TextComp },
  data() {
    return {
      // 模拟接口数据
      newsList: [
        {
          id: 1,
          type: 'TextComp'
        },
        {
          id: 2,
          type: 'TextComp'
        },
        {
          id: 3,
          type: 'ImageComp'
        }
      ]
    }
  }
}
</script>

End----------------------------

猜你喜欢

转载自blog.csdn.net/u011690675/article/details/130259802
今日推荐