动态组件指的是 动态切换组件的显示与隐藏
vue提供了一个内置的<component>组件,专门用来实现动态组件的渲染。
示例代码如下:
Left.vue的代码
<template>
<div class="box">这是左边的组件</div>
</template>
<script>
export default {
name: "Left",
};
</script>
<style lang="less" scoped>
.box {
background-color: pink;
border: 1px solid;
height: 400px;
width: 400px;
color: white;
}
</style>
Right.vue的代码
<template>
<div class="box">这是右边的组件</div>
</template>
<script>
export default {
name: "Right",
};
</script>
<style lang="less" scoped>
.box {
background-color: blue;
border: 1px solid;
height: 400px;
width: 400px;
color: white;
}
</style>
App.vue的代码
<template>
<div id="app">
<div class="content">
<component :is="name"></component>
</div>
<h1>这是一个App组件</h1>
<button @click="name = 'Left'">显示Left</button>
<button @click="name = 'Right'">显示Right</button>
</div>
</template>
<script>
import Left from "@/components/Left";
import Right from "@/components/Right";
export default {
name: "App",
components: {
Left,
Right,
},
data() {
return {
name: "Left",
};
},
};
</script>
<style lang="less">
.content {
display: flex;
}
</style>
使用keep-alive可以保持状态,组件创建后不会被销毁,
那怕被隐藏了也不会被销毁。
使用keep-alive来保持状态
语法
<keep-alive>
<组件名></组件名>
</keep-alvie>
Left.vue的代码
<template>
<div class="box">
<h3>这是左边的组件{{ count }}</h3>
<button @click="count++">+1</button>
</div>
</template>
<script>
export default {
name: "Left",
data() {
return {
count: 0,
};
},
created() {
console.log("Left组件被创建了");
},
destroyed() {
console.log("Left组件被销毁了");
},
};
</script>
<style lang="less" scoped>
.box {
background-color: pink;
border: 1px solid;
height: 400px;
width: 400px;
color: white;
}
</style>
Right.vue的代码
<template>
<div class="box">这是右边的组件</div>
</template>
<script>
export default {
name: "Right",
};
</script>
<style lang="less" scoped>
.box {
background-color: blue;
border: 1px solid;
height: 400px;
width: 400px;
color: white;
}
</style>
App.vue的代码
<template>
<div id="app">
<div class="content">
<keep-alive>
<component :is="name"></component>
</keep-alive>
</div>
<h1>这是一个App组件</h1>
<button @click="name = 'Left'">显示Left</button>
<button @click="name = 'Right'">显示Right</button>
</div>
</template>
<script>
import Left from "@/components/Left";
import Right from "@/components/Right";
export default {
name: "App",
components: {
Left,
Right,
},
data() {
return {
name: "Left",
};
},
};
</script>
<style lang="less">
.content {
display: flex;
}
</style>
实现效果:
因为没有指定哪个组件被缓存,哪个组件不缓存,所以默认被keep-alive包裹的所有组件都会被缓存。
include属性用来指定:只有名称匹配的组件会被缓存。多个组件名之间 使用英文 逗号 分隔。
例如现在有一个需求:Left组件要求被缓存,Right组件不要求被缓存
需求:Right组件不希望被缓存
控制台查看
控制台查看