Vue动态组件和异步组件

43次阅读

共计 2516 个字符,预计需要花费 7 分钟才能阅读完成。

动态组件
如果我们打算在一个地方根据不同的状态引用不同的组件的话,比如 tab 页,那么 Vue 给我们提供动态组件。
基本使用
Parent.vue
<template>
<div>
<el-button-group>
<el-button v-for='(btn, index) in btnGroup’
:key=”index” :class=”{active:btn.disabled}”
@click=’change(index)’>{{btn.name}}
</el-button>
</el-button-group>
<div>
<component :is=’currentCom’></component>
</div>
</div>
</template>
<script>
import Childs1 from ‘./Childs1’
import Childs2 from ‘./Childs2’
import Childs3 from ‘./Childs3’
import Childs4 from ‘./Childs4′

export default {
name:’Parent’,
components:{
Childs1,
Childs2,
Childs3,
Childs4
},
data() {
return {
btnGroup: [
{name: ‘Childs1’, disabled: true},
{name: ‘Childs2’, disabled: false},
{name: ‘Childs3’, disabled: false},
{name: ‘Childs4′, disabled: false},
],
currentCom:’Childs1’

}
},
methods: {
change(index){

let pre = Number(this.currentCom[this.currentCom.length -1]);
this.btnGroup

.disabled = false;
this.btnGroup[index].disabled = true;
this.currentCom = ‘Childs’ + (index + 1);

}
}
}
</script>
<style scoped>
.active{
background-color: red;
}
</style>
运行结果如下图:
当我们点击不同的按钮时,下面会切换不同的组件。实现动态组件的加载。is 的值可以是一个已经注册的组件的名字或者一个组件的选对象。当我们点击按钮时,这个按钮的 disabled 为 true 然后我们将给这个按钮一个 active 的 css 类, 同时改变 currentCom 的值

keep-alive: 动态组件的缓存
如果我们需要频繁的切换页面,每次都是在组件的创建和销毁的状态间切换,这无疑增大了性能的开销。那么我们要怎么优化呢?Vue 提供了动态组件的 缓存。keep-alive 会在切换组件的时候缓存当前组件的状态,等到再次进入这个组件,不需要重新创建组件,只需要从前面的缓存中读取并渲染。
Parent.vue(其余地方代码和上面一样)
<template>
<div>
<el-button-group class=’btn-group’>
<el-button v-for='(btn, index) in btnGroup’
:key=”index” :class=”{active:btn.disabled}”
@click=’change(index)’>
{{btn.name}}
</el-button>
</el-button-group>
<div style=’padding-top:100px;’>
<keep-alive>
<component :is=’currentCom’></component>
</keep-alive>
</div>
</div>
</template>
<style scoped>
.btn-group{
position:fixed;
}
.active{
background-color: red;
}
</style>
Childs1.vue
<template>
<div>
{{title}}
<button @click=’change’> 点我 +1</button>
</div>
</template>
<script>
export default {
name:’Childs1′,
data(){
return{
title: 1
}
},
methods:{
change(){
this.title += 1;
}
},
mounted(){
console.log(‘child1 mounted’);

}
}
</script>
Childs2.vue
<template>
<div>
Childs2
</div>
</template>
<script>
export default {
name:’Childs2′,
mounted(){
console.log(‘child2 mounted’);

}
}
</script>
运行结果如下图:‘
对比:如果我们将 <keep-alive></keep-alive> 去掉,运行结果如下图:

前一组图片在切换组件的时候,title 从 1 加到 3,然后等下次再切换回来的时候,title 还是停留在 3,从控制台可以看出,Childs1.vue 这个组件的 mounted 的钩子函数只有一次。后一组图片,title 一开始加到 3,下一次进入这个组件的时候 title 又从 1 开始,控制台图片也显示这个组件经历个了多次钩子函数,说明组件是销毁重建的。
tips: 因为缓存的组件只需要建立一次,所以如果我们要在每次进入组件的钩子函数里面做相应的操作的时候,会出现问题,所以请明确我们使用的场景,避免出现 bug
异步组件
异步组件存在的意义在于加载一个体量很大的页面时,如果我们不设置加载的优先级的话,那么可能页面在加载视频等信息的时候会非常占用时间,然后主要信息就会阻塞在后面在加载。这对用户来说无疑不是一个很差的体验。但是如果我们设置加载的顺序,那么我们可以优先那些最重要的信息优先显示,优化了整个项目。一般来说我们是将加载组件和 路由(vue-router)配合在一起使用,所以这里我就不细讲了,具体学习可以参考官网来进行学习。

正文完
 0