动态组件(特殊的attribute:is)

时间:2020-05-09
本文章向大家介绍动态组件(特殊的attribute:is),主要包括动态组件(特殊的attribute:is)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

第一种:组件切换

  //三个按钮
 <div id="dynamic-component-demo" class="demo">
      <button
        v-for="tab in tabs"
        v-bind:key="tab"
        v-bind:class="['tab-button', { active: currentTab === tab }]"
        v-on:click="currentTab = tab"
      >
        {{ tab }}
      </button>
    //组件切换
      <component v-bind:is="currentTabComponent" class="tab"></component>
    </div>

    <script>
//组件注册
      Vue.component("tab-home", {
        template: "<div>Home component</div>"
      });
      Vue.component("tab-posts", {
        template: "<div>Posts component</div>"
      });
      Vue.component("tab-archive", {
        template: "<div>Archive component</div>"
      });

      new Vue({
        el: "#dynamic-component-demo",
        data: {
          currentTab: "Home",
          tabs: ["Home", "Posts", "Archive"]
        },
//计算属性:监控组件的变化
        computed: {
          currentTabComponent: function() {
            return "tab-" + this.currentTab.toLowerCase();
          }
        }
      });
    </script>  

第二种:若是切换a和router-link组件,则需要绑定to属性

<template>

  <!-- eslint-disable vue/require-component-is -->

  <component :is="linkProps(to).is" v-bind="linkProps(to)">

    <slot />

  </component>

</template>

 

<script>

import { isExternal } from '@/utils/validate'

 

export default {

  props: {

    to: {

      type: String,

      required: true

    }

  },

  methods: {

    linkProps(url) {

      if (isExternal(url)) {

        return {

          is: 'a',

          href: url,

          target: '_blank',

          rel: 'noopener'

        }

      }

      return {

        is: 'router-link',

        to: url

      }

    }

  }

}

</script>
 

参考:https://blog.csdn.net/xiaoxiaoluckylucky/article/details/100603618

原文地址:https://www.cnblogs.com/star-meteor/p/12857621.html