如何实现一个组件的切换显示呢?
前台控制两个组件使用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>
直接这样调用就行!动态判断组件的显示
向上述就是那个符合条件显示在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>
这样处理静态资源比较好,第一次会进行加载并写入到内存中,下次使用的时候直接从内存取出就行,无需进行组件新建!