Vue高級特性「七」--動態組件\異步組件***

使用場景:
需要根據數據(新聞詳情頁),動態渲染的場景,即組件類型不確定。

動態組件基本使用

<component :is="nextTickName"></component>

import nextTick from './nextTick'
export default {
  components:{
    nextTick,
  },
  data() {
    return {
      nextTickName:"nextTick"
    };
  },
  
};

用動態組件實現切換

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

new Vue({
  el: '#example',
  data:{
    index:0,
    arr:[
      {template:`<div>我是頁面A</div>`},
      {template:`<div>我是頁面B</div>`},
      {template:`<div>我是頁面C</div>`}
    ],
  },
  computed:{
    currentView(){
        return this.arr[this.index];
    }
  },
  methods:{
    change(){
      this.index = (++this.index)%3;
    }
  }
})

什麼是異步組件?

異步組件就是定義的時候什麼都不做,只在組件需要渲染(組件第一次顯示)的時候進行加載渲染並緩存,緩存是以備下次訪問。

Vue實現按需加載

  • import() 函數
  • 按需加載,異步加載大組件

註冊方式:

components:{
  FromDemo:()=>import('../FromDemo')
}

組件調用方式:

<FromDemo v-if="show"/>
<button @click="show=true"></button>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章