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>

 

 

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM