HMVue6.1【动态组件】


1 初始项目

 npm install

npm audit fix

<template>
<div class="app-container">
    <h1>App 根组件h1>
    <hr>
    <div class="box">
        
    div>
div>
template>

<script>
export default {}
script>

<style lang="less">
.app-container {
  padding: 1px 20px 20px;
  background-color: #efefef;
}
.box {
  display: flex;
}
style>
<template>
<div class="left-container">
    <h3>Left 组件h3>
div>
template>

<script>
export default {}
script>

<style lang="less">
.left-container {
  padding: 0 20px 20px;
  background-color: orange;
  min-height: 250px;
  flex: 1;
}
style>
<template>
<div class="right-container">
    <h3>Right 组件h3>
div>
template>

<script>
export default {}
script>

<style lang="less">
.right-container {
  padding: 0 20px 20px;
  background-color: lightskyblue;
  min-height: 250px;
  flex: 1;
}
style>

npm run serve

http://localhost:8080/

2 课件

3 动态组件 的基本使用

 

4 使用组件保持状态

4-1 问题分析

 

 在离开Left进入Right时,Left被销毁了;从Right回到Left时,是一个新的Left,而不是原来的Left,所以原先Left的数据没了

4-2 问题验证

 

 4-2 解决问题

4-2-1

 

 4-2-2

 

 4-2-3

 

 4-2-4

 

 inactive意思:失活、未激活、被缓存

5 keep-alive对应的生命周期函数

 

6 keep-alive的include和exclude属性

注意:这两个属性不能同时使用,只能使用其中一个或者不用

 

 Right在被切出的状态下直接被销毁,而Left会被缓存而不会被销毁(include="Left" 或 exclude="Right" 效果一致)

7 扩展:组件注册名称与组件声明时name的区别

8 源码

<template>
<div class="app-container">
    <h1>App 根组件h1>
    <hr>
    <button @click="comName='Left'">展示Leftbutton>
    <button @click="comName='Right'">展示Rightbutton>
    
    <div class="box">
        
        

        
          
         
         

        
        
        
        

        
        <keep-alive>  
            <component :is="comName">component>
        keep-alive>
    div>
div>
template>



<script>
import Left from '@/components/Left.vue'
import Right from '@/components/Right.vue'

export default {
    data(){
        return{
            //comName 表示要展示的组件的名字
            comName: 'Right'
        }
    },
    components: {
        //如果在“声明组件export default”的时候,没有为组件指定 name属性 名称(/值),则组件的名称默认就是“注册components时候的名称”。
        // (1) components注册名称主要作用:在