Vue的动态组件是什么?什么用?

1、 什么是动态组件?

动态组件,就是实现动态切换的组件css

记住如下三点,就能掌握动态组件html

① 利用 <component/> 元素的 is 属性vue

is 属性应该用 v-bind 修饰(能够简写为 :git

is属性应该传入注册的组件名github

举个例子vue-cli

在我 vue-cli 工程中有组件A和B缓存

A和B组件分别是这样markdown

<template>
  <div>
    组件A
  </div>
</template>
复制代码
<template>
  <div>
    组件B
  </div>
</template>
复制代码

是的,就是这么简单的...cookie

<template>
  <div>
    <component :is="showComp" />
    <button @click="switchComp">切换组件B</button>
  </div>
</template>

<script>
import AComp from '../components/AComp'
import BComp from '../components/BComp'
export default {
  components: { // 组件注册
    AComp,
    BComp
  },
  data () {
    return { // showComp 指向 A组件
      showComp: 'AComp'
    }
  },
  methods: {
    switchComp () { // 点击按钮变为 B组件
      this.showComp = 'BComp'
    }
  }
}
</script>
复制代码

2、应用场景

1.List列表

这种列表彻底能够适用于 动态组件app

只要设计好数据局结构

好比:

<template>
  <div>
    <component
      v-for="(item, index) in compList"
      :is="item.compName"
      :data="item.data"
      :key="index"
    />
  </div>
</template>

<script>
import AComp from '../components/AComp'
import BComp from '../components/BComp'
export default {
  components: {
    AComp,
    BComp
  },
  data () {
    return {
      compList: [
        {
          compName: 'AComp', // 使用A组件
          data: {
            // 赋值给A组件的数据
            // ...
          }
        },
        {
          compName: 'BComp', // 使用B组件
          data: {
            // 赋值给B组件的数据
            // ...
          }
        }
        // 以此类推...
      ]
    }
  }
}
</script>
复制代码

2. tab标签页

vue官网介绍这种场景

其实和List列表大同小异

你们能够看看源码

<!DOCTYPE html>
<html>
  <head>
    <title>Vue Component Blog Post Example</title>
    <script src="https://unpkg.com/vue"></script>
    <link rel="stylesheet" type="text/css" href="/style.css" />
  </head>
  <body>
    <div id="dynamic-component-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>

      <keep-alive>
        <component v-bind:is="currentTabComponent" class="tab"></component>
      </keep-alive>
    </div>

    <script>
      Vue.component("tab-posts", {
        data: function() {
          return {
            posts: [
              {
                id: 1,
                title: "Cat Ipsum",
                content:
                  "<p>Dont wait for the storm to pass, dance in the rain kick up litter decide to want nothing to do with my owner today demand to be let outside at once, and expect owner to wait for me as i think about it cat cat moo moo lick ears lick paws so make meme, make cute face but lick the other cats. Kitty poochy chase imaginary bugs, but stand in front of the computer screen. Sweet beast cat dog hate mouse eat string barf pillow no baths hate everything stare at guinea pigs. My left donut is missing, as is my right loved it, hated it, loved it, hated it scoot butt on the rug cat not kitten around</p>"
              },
              {
                id: 2,
                title: "Hipster Ipsum",
                content:
                  "<p>Bushwick blue bottle scenester helvetica ugh, meh four loko. Put a bird on it lumbersexual franzen shabby chic, street art knausgaard trust fund shaman scenester live-edge mixtape taxidermy viral yuccie succulents. Keytar poke bicycle rights, crucifix street art neutra air plant PBR&B hoodie plaid venmo. Tilde swag art party fanny pack vinyl letterpress venmo jean shorts offal mumblecore. Vice blog gentrify mlkshk tattooed occupy snackwave, hoodie craft beer next level migas 8-bit chartreuse. Trust fund food truck drinking vinegar gochujang.</p>"
              },
              {
                id: 3,
                title: "Cupcake Ipsum",
                content:
                  "<p>Icing dessert soufflé lollipop chocolate bar sweet tart cake chupa chups. Soufflé marzipan jelly beans croissant toffee marzipan cupcake icing fruitcake. Muffin cake pudding soufflé wafer jelly bear claw sesame snaps marshmallow. Marzipan soufflé croissant lemon drops gingerbread sugar plum lemon drops apple pie gummies. Sweet roll donut oat cake toffee cake. Liquorice candy macaroon toffee cookie marzipan.</p>"
              }
            ],
            selectedPost: null
          };
        },
        template: `
   <div class="posts-tab">
      <ul class="posts-sidebar">
        <li
          v-for="post in posts"
          v-bind:key="post.id"
          v-bind:class="{ selected: post === selectedPost }"
     v-on:click="selectedPost = post"
        >
          {{ post.title }}
        </li>
      </ul>
      <div class="selected-post-container">
       <div 
         v-if="selectedPost"
          class="selected-post"
        >
          <h3>{{ selectedPost.title }}</h3>
          <div v-html="selectedPost.content"></div>
        </div>
        <strong v-else>
          Click on a blog title to the left to view it.
        </strong>
      </div>
    </div>
  `
      });

      Vue.component("tab-archive", {
        template: "<div>Archive component</div>"
      });

      new Vue({
        el: "#dynamic-component-demo",
        data: {
          currentTab: "Posts",
          tabs: ["Posts""Archive"]
        },
        computed: {
          currentTabComponent: function() {
            return "tab-" + this.currentTab.toLowerCase();
          }
        }
      });
    </script>
  </body>
</html>

复制代码

不一样是,官网介绍了能够添加 keep-alive 这个组件进行缓存

感谢阅读

相关文章
相关标签/搜索