如何實作一個元件的切換顯示呢?
動态元件
前台控制兩個元件使用v-if條件渲染,給一個按鈕一個切換方法
<child-one v-if="type=='child-one'" v-once></child-one>
<child-two v-if="type=='child-two'" v-once></child-two>
<button @click="qiehuan">切換</button>
複制
定義兩個元件以及這個vue執行個體的切換方法實作
Vue.component('child-one',{
template:`
<h3 >child-one</h3>
`
})
Vue.component('child-two',{
template:`
<h3>child-two</h3>
`
})
//Vue執行個體切換
var app=new Vue({
el:"#app",
data:{
type:"child-one"
},
methods:{
qiehuan:function(){
this.type=this.type=="child-one"?"child-two":"child-one"
}
}
})
複制
這樣是不是有點麻煩?我們可以動态的顯示?使用component元件綁定is
<component :is="type" ></component>
複制
直接這樣調用就行!動态判斷元件的顯示
v-once
向上述就是那個符合條件顯示在dom中,不符合的則直接在dom中銷毀,這樣是比較性能地下,如何正确的使用呢?可以加載一個v-once屬性
<child-one v-if="type=='child-one'" v-once></child-one>
<child-two v-if="type=='child-two'" v-once></child-two>
<button @click="qiehuan">切換</button>
複制
這樣處理靜态資源比較好,第一次會進行加載并寫入到記憶體中,下次使用的時候直接從記憶體取出就行,無需進行元件建立!