天天看點

vue動态切換元件

實作動态切換元件

  • 使用

    <component is="元件名"></component>

    component為内置元件,使用 is = “元件名”,就會自動去找比對的元件(即is的值寫的是哪個元件,component就代表的是哪個元件)

    想要改變挂載的元件,隻需要修改is對應的值即可

html

<template>
    <div :style="{border: '1px solid red'}">
    
      <button @click="pButton1(0)">Path1</button>
      <button @click="pButton2(1)">Path2</button>
      
     <keep-alive >
        <component :is="pageName"/>
     </keep-alive>
     
    </div>
</template>
           

js

<script>
import Path1 from "components/Path1.vue";
import Path2 from "components/Path2.vue";

export default {
  data() {
    return {
      isActive: 0
    };
  },
  components: {
    Path1,
    Path2
  },
  //使用計算屬性
  computed: {
    pageName() {
      switch (this.isActive) {
        case 0:
          return "Path1";
          break;

        default:
          return "Path2";
          break;
      }
    }
  },
  methods: {
    pButton1(index) {
      this.isActive = index;
    },
    pButton2(index) {
      this.isActive = index;
    }
  }
};
</script>
           
  • 其中,點選按鈕判斷是否顯示哪個路由時,可用另一種方法v-if/v-else來進行操作(上面一種是使用計算屬性的),以下是代碼
<Path1 v-if="isActive==0"></Path1>
 <Path1 v-else></Path1>
           
  • 使用元件

    keep-alive

    進行緩存

    元件之間切換的時候,保持這些元件的狀态,以避免反複重渲染導緻的性能問題;

    包裹動态組建時,會緩存不活動的元件執行個體,而不是銷毀它們

  • 其中使用include,表示隻有名稱比對的路由才可以被緩存
  • 比對規則

    比對首先檢查元件自身的 name 選項,如果 name 選項不可用,則比對它的局部注冊名稱 (父元件 components 選項的鍵值)

<keep-alive include="Path1">
        <component :is="pageName"/>
</keep-alive>
           
vue動态切換元件
vue