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>
<script>
Vue.component("child-one",{
template: '<div>child1</div>'
})
Vue.component("child-two",{
template: '<div>child2</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 标签,该标签的绑定属性 is 则指它实际上是哪个组件。
代码如下。
<div id="root">
<component :is="type"></component>
<button @click="handleBtnClick">change</button>
</div>
<script>
Vue.component("child-one",{
template: '<div>child1</div>'
})
Vue.component("child-two",{
template: '<div>child2</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>
v-once 指令,使用如下。该指令会使dom 第一次展示的时候,放入内存里,以后使用的时候读出内存即可。可以提高一些静态内容的展示效率。
<div id="root">
<!-- <component :is="type"></component> -->
<child-one v-if="type === 'child-one'"></child-one>
<child-two v-if="type === 'child-two'"></child-two>
<button @click="handleBtnClick">change</button>
</div>
<!-- v-once -->
<script>
Vue.component("child-one",{
template: '<div v-once>child1</div>'
})
Vue.component("child-two",{
template: '<div >child2</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>