十一、动态组件与v-once指令
2019-03-20 本文已影响0人
李浩然_6fd1
<body>
<div id="root">
<child-one></child-one>
<child-two></child-two>
<button>change</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"
})
</script>
</body>
这个代码的页面显示是:
![](https://img.haomeiwen.com/i14557673/496499cfc87d728c.png)
现在有一个需求:child-one、child-two屏幕上显示一个,当点击change按钮的时候,显示的将变成另一个。
修改后的代码如下:
<body>
<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>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>
</body>
除了这样编写,还可以通过动态组件的方式来编写代码
<body>
<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>
<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>
</body>
div标签内有个component标签,这个标签是Vue自带的一个动态组件,这个component标签有个属性is,属性is绑定数据type。
这样页面的显示和刚才的一模一样。
动态组件的优势是其is所绑定的数据的变化自动的加载不同的组件。比如一开始type是child-one,那么component会加载child-one组件,当点击按钮后,type变成child-two,那么动态组件就会销毁child-one组件,显示child-two组件。
v-once指令
如上面例子的代码,当按钮切换child-one和child-two时,系统都会销毁一个组件然后建立另一个组件。这样是会消耗一定的性能。
如果当我切换的时候,要销毁的数据我把它当缓存保存下来,这样下次用到的时候就不用消耗性能了。这就用到了v-once。
修改后的代码如下
<body>
<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>
<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>
</body>
如上,被v-once修饰过的内容可以被内存保存下来,这样,下次再次用到的时候就可以直接拿来用。