vue使用之动态组件

有的时候,在不同组件之间进行动态切换是非常有用的,比如在一个多标签的界面里:

上述内容可以通过 Vue 的 <component> 元素加一个特殊的 is 特性来实现:

<!-- 组件会在 `currentTabComponent` 改变时改变 -->
<component v-bind:is="currentTabComponent"></component>

在上述示例中,currentTabComponent 可以包括

已注册组件的名字,或
一个组件的选项对象

下面贴一个已经实现好的例子提供大家参考:

<template>
  <div class="three">
    <button
      v-for="item in tabs"
      :key="item"
      :class="['tab-button',{active:currentTab === item}]"
      @click="currentTab = item"
    >{{item}}</button>
    <component :is="currentTabComponent" class="tab"></component>
  </div>
</template>

<script>
import first from '@/components/First.vue'
import second from '@/components/Second.vue'
import third from '@/components/Third.vue'
export default {
  name: 'three',
  components: {
    first,
    second,
    third
  },
  data () {
    return {
      currentTab: 'first',
      tabs: ['first', 'second', 'Third']
    }
  },
  computed: {
    currentTabComponent () {
      return this.currentTab.toLowerCase()
    }
  },
  mounted () {},
  methods: {},
}
</script>

<style lang="less" scoped>
.three {
  .tab-button {
    padding: 6px 10px;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    border: 1px solid #ccc;
    cursor: pointer;
    background: #f0f0f0;
    margin-bottom: -1px;
    margin-right: -1px;
  }
  .tab-button:hover {
    background: #e0e0e0;
  }
  .tab-button.active {
    background: #e0e0e0;
  }
  .tab {
    border: 1px solid #ccc;
    padding: 10px;
  }
}
</style>

效果如下:
在这里插入图片描述
点击切换的时候就会切换到相应的组件当中去。

如果这个时候,切换回原来的组件需要缓存的话,就需要加一个<keep-alive></keep-alive>标签了,关于这个标签,可以参考我的这篇文章在vue中使用keepalive
这里first组件将会缓存

<template>
  <div class="three">
    <button
      v-for="item in tabs"
      :key="item"
      :class="['tab-button',{active:currentTab === item}]"
      @click="currentTab = item"
    >{{item}}</button>
    <keep-alive include="first">
      <component :is="currentTabComponent" class="tab"></component>
    </keep-alive>
  </div>
</template>
发布了53 篇原创文章 · 获赞 59 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42268364/article/details/102385063