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 這個組件進行緩存

感謝閱讀

相關文章
相關標籤/搜索