場景,點擊某個按鈕,兩個子組件交替顯示
<div id='root'> <child-one v-if='type==="child-one"'></child-one> <child-two v-if='type==="child-two"'></child-two> <button @click='handleBtnClick'>Button</button> </div> <script> Vue.component('child-one',{ template:'<div>child-one</div>' }) Vue.component('child-two',{ template:'<div>child-two</div>' }) var vm = new Vue({ el:'#root', data:{ type:'child-one' }, methods:{ handleBtnClick:function(){ this.type = (this.type === 'child-one' ? 'child-two' : 'child-one') } } }) </script>
除了上述的寫法,有沒有另外一種寫法呢?可以通過動態組件的形式來編寫這段代碼
標簽component
<div id='root'> <component :is='type'></component> <button @click='handleBtnClick'>Button</button> </div> <script> Vue.component('child-one',{ template:'<div>child-one</div>' }) Vue.component('child-two',{ template:'<div>child-two</div>' }) var vm = new Vue({ el:'#root', data:{ type:'child-one' }, methods:{ handleBtnClick:function(){ this.type = (this.type === 'child-one' ? 'child-two' : 'child-one') } } }) </script>
把兩個子組件用<component>代替,效果一模一樣,component會根據數據的變化,自動加載不同的組件,一開始進來,type的值是child-one,這個時候就會去加載child-one這個組件
在第一個例子中,每次切換都要銷毀一個組件,再創建一個組件,這個效率會比較低,如果可以把組件放到內存中效率就會有所提高
v-once
<div id='root'> <child-one v-if='type==="child-one"'></child-one> <child-two v-if='type==="child-two"'></child-two> <button @click='handleBtnClick'>Button</button> </div> <script> Vue.component('child-one',{ template:'<div v-once>child-one</div>' }) Vue.component('child-two',{ template:'<div v-once>child-two</div>' }) var vm = new Vue({ el:'#root', data:{ type:'child-one' }, methods:{ handleBtnClick:function(){ this.type = (this.type === 'child-one' ? 'child-two' : 'child-one') } } }) </script>