vue-动态组件(:is=“组件名“)
通过使用保留的 元素,动态地绑定到它的 is 特性,我们让多个组件可以使用同一个挂载点,并动态切换不同的组件。根据 v-bind:is=“组件名” 中的组件名去自动匹配组件 也是一个组件对象,如果匹配不到则不显示。
也可以用做不改变路由的情况下切换不同的页面/组件。
改变挂载的组件,只需要修改is指令的值即可。不会保存组件的状态(即重新加载这个组件)
实现tab动态切换三个组件
<component :is="currentView" class="table"></component>
<script>
import ThemeWork from './components/themeWork'
import Banner from './components/banner'
import Links from './components/link'
export default {
components: {
ThemeWork,
Banner,
Links
},
data() {
return {
arr: ['Banner', 'ThemeWork', 'Links'],
navList: [
{ label: 0, value: '轮播设置' },
{ label: 1, value: '作品集管理' },
{ label: 2, value: '学习资源管理' }
],
activeIndex: 0,
}
},
computed: {
currentView() {
return this.arr[this.activeIndex]
}
},
methods: {
// 切换
handleNav(index) {
this.activeIndex = index
}
}
}
</script>
缓存
上述讲到的方法虽然能够实现了动态组件的切换,但是每次切换都会把上一个组件销毁,然后渲染下一个组件,对于多次切换而言,显然每次的销毁和重新渲染,很大消耗了我们的性能。所以我们可以通过keep-alive对组件进行缓存,对于不显示的组件不是去销毁,而是处于不激活的状态,当需要显示时再激活。
keep-alive 两个属性include和exclude
include表示只能允许匹配到的组件生效
exclude则相反,除了匹配到的组件之外有效
<!-- 字符串 逗号分隔字符串, a,b 分别为组件名 -->
<keep-alive include="a,b">
<component :is="currentView"></component>
</keep-alive>
<!-- 正则表达式 -->
<keep-alive :include="/a|b/">
<component :is="currentView"></component>
</keep-alive>
<!-- 数组 -->
<keep-alive :include="['a', 'b']">
<component :is="currentView"></component>
</keep-alive>
说明:
activated 和 deactivated 这两个生命周期钩子函数将会被对应执行,只有使用缓存子组件才存在这两个钩子函数。
可以延迟执行当前的组件。
具体用法来说,activate是和template、data等属性平级的一个属性,形式是一个函数,函数里默认有一个参数,而这个参数是一个函数,执行这个函数时,才会切换组件。
// Links.vue 子组件
<template>
<div>{{msg}} --- {{hello}}</div>
</template>
<script>
export default {
name: "Links",
data() {
return {
msg: "组件2",
hello: ""
};
},
activated(done) {
//执行这个参数时,才会切换组件
console.log("组件被添加");
// var self = this;
var startTime = new Date().getTime(); // get the current time
//两秒后执行
while (new Date().getTime() < startTime + 2000) {
this.hello = "我是延迟后的内容";
}
},
deactivated() {
console.log("组件被移除");
this.$emit('passData', "组件被移除");
}
};
</script>