<template>
<div>
<keep-alive>
<component :is="currentTab"></component>
</keep-alive>
<button @click="changeTab(1)">页签1</button>
<button @click="changeTab(2)">页签2</button>
<button @click="changeTab(3)">页签3</button>
</div>
</template>
<script>
import tab1 from "@/components/tabs/tab1 ";
import tab2 from "@/components/tabs/tab2 ";
import tab3 from "@/components/tabs/tab3 ";
export default({
name: "pageManage",
components: {tab1, tab2, tab3},
data: {
return{
currentTab: 'tab1'
}
},
methods: {
changeTab: function(index){
this.currentTab= 'tab'+ index
}
}
});
</script>
通过使用保留的component元素,动态绑定到is 属性来切换不同组件
解释一下组件外面的keep-alive:
如果不加keep-alive,每次切换组件的时候都创建了新的vue实例,之前的状态将不会被保存
由于业务需要,有时我们更希望那些标签的组件实例能够被在它们第一次被创建的时候缓存下来。为了解决这个问题,我们可以用一个 keep-alive元素将其动态组件包裹起来。
是否使用根据业务需求判定