Article directory
dynamic components
1. Dynamic Components
Dynamic components refer to dynamically switching the display and hiding of components. Vue provides a built-in <component>
component , which is specially used to achieve dynamic rendering of components.
①It
<component>
is the placeholder of the component ②
Dynamically specify the name of the component to be rendered through the is attribute③<component is="要渲染的组件的名称"></component>
2. Implement dynamic component rendering
<template>
<div>
<h1>App 组件</h1>
<!-- 切换组件的按钮 -->
<button @click="comName='Com_1'"> 显示组件1 </button>
<button @click="comName='Com_2'"> 显示组件2 </button>
<hr>
<!-- 动态组件显示区域 -->
<component :is="comName"></component>
</div>
</template>
<script>
import Com_1 from './Com_1.vue'
import Com_2 from './Com_2.vue'
export default {
name: 'App',
data() {
return {
// 组件名字
comName: ''
}
},
components: {
Com_1,
Com_2
}
}
</script>
<style>
</style>
<template>
<div>
<h3>Com_1 组件</h3>
</div>
</template>
<script>
export default {
name: 'Com_1'
}
</script>
<style>
</style>
<template>
<div>
<h3>Com_2 组件</h3>
</div>
</template>
<script>
export default {
name: 'Com_2'
}
</script>
<style>
</style>
3. Use keep-alive to keep state
By default, the state of a component cannot be maintained when switching dynamic components. At this point, you can use vue's built-in <keep-alive>
components to maintain the state of dynamic components.
The component states corresponding to the above three states:
When switching components, components are dynamically destroyed and created.
Maintain the state of dynamic components
Add a layer outside the dynamic component<keep-alive>
<!-- 动态组件显示区域 -->
<keep-alive>
<component :is="comName"></component>
</keep-alive>
<template>
<div>
<h1>App 组件</h1>
<!-- 切换组件的按钮 -->
<button @click="comName='Com_1'"> 显示组件1 </button>
<button @click="comName='Com_2'"> 显示组件2 </button>
<hr>
<!-- 动态组件显示区域 -->
<keep-alive>
<component :is="comName"></component>
</keep-alive>
</div>
</template>
<script>
import Com_1 from './Com_1.vue'
import Com_2 from './Com_2.vue'
export default {
name: 'App',
data() {
return {
// 组件名字
comName: ''
}
},
components: {
Com_1,
Com_2
}
}
</script>
<style>
</style>
Adding a layer outside the dynamic component <keep-alive>
will cache the component state, will not destroy the component, will dynamically activate the component, and maintain the component state.