国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Vue 動態組件與 v-once 指令的實現

2019-11-19 12:09:43
字體:
來源:轉載
供稿:網友

本文介紹了Vue 動態組件與 v-once 指令的實現,分享給大家,具體如下:

<div id="root">  <child-one></child-one>  <child-two></child-two>  <button>change</button></div>Vue.component('child-one', {  template: `<div>child-one</div>`,})Vue.component('child-two', {  template: `<div>child-two</div>`,})let vm = new Vue({  el: '#root'})

上面代碼需實現,當點擊按鈕時,child-one和child-two實現toggle效果,該怎么實現呢?

<div id="root">  <child-one v-if="type === 'child-one'"></child-one>  <child-two v-if="type === 'child-two'"></child-two>  <button @click="handleBtnClick">change</button></div>Vue.component('child-one', {  template: `<div>child-one</div>`,})Vue.component('child-two', {  template: `<div>child-two</div>`,})let vm = new Vue({  el: '#root',  data: {    type:'child-one'  },  methods: {    handleBtnClick(){      this.type = this.type === 'child-one' ? 'child-two' : 'child-one'    }  }})

通過上面handleBtnClick函數的實現,配合v-if指令就能實現toggle效果

動態組件

下面這段代碼實現的效果和上面是一樣的。

<div id="root">  <component :is="type"></component>   //is內容的變化,會自動的加載不同的組件  <button @click="handleBtnClick">change</button></div>Vue.component('child-one', {  template: `<div>child-one</div>`,})Vue.component('child-two', {  template: `<div>child-two</div>`,})let vm = new Vue({  el: '#root',  data: {    type:'child-one'  },  methods: {    handleBtnClick(){      this.type = this.type === 'child-one' ? 'child-two' : 'child-one'    }  }})

動態組件的意思是它會根據is里面數據的變化,會自動的加載不同的組件

v-noce指令

每次點擊按鈕切換的時候,Vue 底層會幫我們干什么呢?Vue 底層會判斷這個child-one組件現在不用了,取而代之要用child-two組件,然后它就會把child-one組件銷毀掉,在創建一個child-two組件。假設這時child-two組件要隱藏,child-one組件要顯示,這個時候要把剛剛創建的child-two銷毀掉,在重新創建child-one組件,也就是每一次切換的時候,底層都是要銷毀一個組件,在創建一個組件,這種操作會消耗一定的性能。如果我們的組件的內容,每次都是一樣的可以在上面加一個v-once,看下面代碼。

Vue.component('child-one', {  template: `<div v-once>child-one</div>`,})Vue.component('child-two', {  template: `<div v-once>child-two</div>`,})

加上v-once指令之后,有什么好處呢?當chlid-one組件第一次被渲染時,因為組件上面有一個v-once指令,所以它直接就放到內存里了,當切換的時候child-two組件第一次被渲染時,它也會被放到內存里,再次點擊切換時,這時并不需要再重新創建一個child-one組件了,而是從內存里直接拿出以前的child-one組件,它的性能會更高一些。

所以在 Vue 當中,通過v-once指令,可以提高一些靜態內容的展示效率

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 漳浦县| 临海市| 秀山| 合阳县| 八宿县| 得荣县| 确山县| 治多县| 江达县| 繁峙县| 分宜县| 枣庄市| 庄河市| 当阳市| 孟津县| 连平县| 金华市| 视频| 巫溪县| 扎囊县| 厦门市| 西青区| 耒阳市| 开鲁县| 黄山市| 陆良县| 基隆市| 宁城县| 新巴尔虎右旗| 卓尼县| 当阳市| 尚志市| 三台县| 徐闻县| 永新县| 平罗县| 修水县| 海阳市| 桐庐县| 武夷山市| 湖南省|