當定義好多組組件後,可以透過條件判斷來決定要出現哪種組件,實際在網頁上常用到的例子如tab的切換。
-tab示意圖-
透過Vue的comonent元素加上v-bind:is可以做出切換的效果,tab內容呈現部分先建立兩個不同的組件元素分別是my-content1和my-content2:
Vue.component('my-component1', {
    template: `
    <div>
      <h3>--component1--</h3>
      <select>
        <option>0</option>
        <option>1</option>
        <option>2</option>
      </select>
    </div>`,
  });
  Vue.component('my-component2', {
    template: `
    <div>
      <h3>--component2--</h3>
    </div>
    `
  });
  new Vue({
    el: "#app",
    data: {
      content: 'my-component1'
    }
  });
組件元素加上v-bind:is特性,is的值放要出現的組件名稱,這裡綁定在data的content上,藉由點擊button來改變content的值:
<div id="app">
    <button @click="content='my-component1'">1</button>
    <button @click="content='my-component2'">2</button>
    <component :is="content"></component>
  </div>
然後就完成了一個簡略的tab了~~~~
但這邊就遇到一個問題...
有沒有注意到當我切換tab時,原先選的option狀態又回到初始了,這是因為在切換的時候Vue會直接把DOM上的組件消滅再重render一份,所以如果想保留狀態的話記得在component外多包一層keep-alive標籤:
  <keep-alive>
      <component :is="content"></component>
    </keep-alive>

狀態留住的感覺真好啊.....太讚讚了
以上為Vue組件的動態切換筆記,明天props![]()