1. 程式人生 > 實用技巧 >vue中的動態元件(component & keep-alive)

vue中的動態元件(component & keep-alive)

  多個元件使用同一個掛載點,並且進行動態的切換這就是動態元件。

  通過使用<component>元素動態的繫結到它的is特性,來實現動態元件

<div id="test">
  <button @click="change">切換頁面</button>
  <component :is="currentView"></component>
</div>

<script>
let home = {template:'<div>home</div>'};
let post = {template:'
<div>post</div>'}; let end = {template:'<div>end</div>'}; new Vue({ el: '#test', components: { home, post, end }, data:{ index:0, arr:['home','post','end'], }, computed:{ currentView(){ return this.arr[this.index]; } }, methods:{ change(){
this.index = (++this.index)%3; } } }) </script>

  使用動態元件來回切換時,元件是要被銷燬的,若不想讓資料銷燬可以使用<keep-alive>,它可以包裹動態元件,這樣就不會被銷燬。如果多個有條件性的子元素,<keep-alive>要求同時只有一個子元素被渲染。

<div id="test">
  <button @click="change">切換頁面</button>
  <keep-alive>
    <component :is="currentView
"></component> </keep-alive> </div>

  當元件在<keep-alive>內切換它的activated和deactivated這兩個生命週期鉤子函式將會被執行。activated和deactivated這兩外鉤子函式是專門為<keep-alive>服務的 。

  include和exclude屬性允許元件有條件地進行快取,二都都可以用逗號分隔字串,正則或者是一個數組來表示。

<div id="example">
  <button @click="change">切換頁面</button>
  <keep-alive>
    <component :is="currentView" @pass-data="getData"></component> 
  </keep-alive>
  <p>{{msg}}</p>
</div><script>
new Vue({
  el: '#example',
  data:{
    index:0,
    msg:'',    
    arr:[
      { 
        template:`<div>我是主頁</div>`,
        activated(){
          this.$emit('pass-data','主頁被新增');
        },
        deactivated(){
          this.$emit('pass-data','主頁被移除');
        },        
      },
      {template:`<div>我是提交頁</div>`},
      {template:`<div>我是存檔頁</div>`}
    ],
  },
  computed:{
    currentView(){
        return this.arr[this.index];
    }
  },
  methods:{
    change(){
      var len = this.arr.length;
      this.index = (++this.index)% len;
    },
    getData(value){
      this.msg = value;
      setTimeout(()=>{
        this.msg = '';
      },500)
    }
  }
})
</script>
<!-- 逗號分隔字串 -->
<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>
<!-- 正則表示式 (使用 v-bind) -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>
<!-- Array (use v-bind) -->
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive>