动态组件
相关api
<!-- 失活的组件将会被缓存!-->
<keep-alive include="Tab1,Tab2">
<component :is="currentTabComponent"></component>
</keep-alive>
component属性
- is=“全局注册或局部注册的组件名”
keep-alive属性
- include string | RegExp | Array 名称匹配(组件中的name选项值)的组件会被缓存
- exclude string | RegExp | Array 名称匹配(组件中的name选项值)的组件不被缓存
- max 最多缓存组件数。一旦这个数字达到了,在新实例被创建之前,已缓存组件中最久没有被访问的实例会被销毁掉。
生命周期函数
- activated 被 keep-alive 缓存的组件激活时调用。
- deactivated 被 keep-alive 缓存的组件失活时调用。
vue生命周期函数
Tab栏切换
App.vue
<template>
<div>
<button v-for="(item, index) in tabsTitle" :key="item" @click="handleClick(index)"
:class="{ active: curIndex === index }">{{ item }}</button>
<!-- <template v-if="curIndex === 0">
<tab-1></tab-1>
</template>
<template v-else-if="curIndex === 1">
<tab-2></tab-2>
</template> -->
<keep-alive include="Tab1, Tab2">
<component :is="tabsTitle[curIndex]"></component>
</keep-alive>
</div>
</template>
<script>
import Tab1 from './components/Tab1.vue'
import Tab2 from './components/Tab2.vue'
export default {
data() {
return {
tabsTitle: ['tab1', 'tab2'],
curIndex: 0
}
},
components: { Tab1, Tab2 },
methods: {
handleClick(index) {
this.curIndex = index
}
}
}
</script>
<style scoped>
.active {
color: pink;
}
</style>
Tab1.vue
<template>
<div>
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name:'Tab1',
data() {
return {
msg: 'tab1'
}
}
}
</script>
Tab2.vue
<template>
<div>
<button @click="count++">{{ count }}</button>
</div>
</template>
<script>
export default {
data() {
return {
count:0
}
}
}
</script>
异步组件
打包
默认业务代码全部打包到app.xxx.js中
import xx from ‘xx’ 导入模块不分包
import()函数导入模块会分包,函数返回值为promise对象
使用异步组件
方式1 传入工厂函数
方式1 传入配置对象