1.动态组件

7/22/2022 vue

# 动态组件和插槽

# 1 动态组件

# 1.1 内部组件component 组件的使用

# 1.1.1 概念和使用

  • Vue内部提供的组件component组件作用是:实现动态的渲染组件,按需显示组件。
  • component 标签是 vue 内置的,作用:组件的占位符
  • is 属性的值,表示要渲染的组件的名字
  • is 属性的值,应该是组件在 components 节点下的注册名称
  • 比如我们这里有两个组件Left和Right,需求:在app根组件中点击按钮可以按需显示组件。
  • 下面是部分关键代码:
<template>
  <div class="app-container">
    <h1>App 根组件</h1>
    <hr />
    <button @click="comName = 'Left' ">展示Left组件</button>
    <button @click="comName = 'Right' ">展示Right组件</button>

    <div class="box">
      <!-- 渲染 Left 组件和 Right 组件 -->
      <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:'Left'
    }
  },
    components:{
    Right,
    Left
  },
}
    
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

# 1.1.2 运行截图

默认显示Left组件

image-20220720161037131

点击展示,显示Right组件:

image-20220720161124831

# 1.2 内部组件 keep-alive 组件的使用

# 1.2.1概念和使用

  • keep-alive 会把内部的组件进行缓存,而不是销毁组件;
  • 在使用 keep-alive 的时候,可以通过 include 指定哪些组件需要被缓存;
  • 或者,通过 exclude 属性指定哪些组件不需要被缓存;但是:不要同时使用 include 和 exclude 这两个属性

keep-alive组件直接包裹component组件,即可实现默认包裹的都会缓存,而不是切换到Right组件,再切回来,Lift组件就要重新创建。

<keep-alive exclude="MyRight">
     <component :is="comName"></component>
</keep-alive>
1
2
3

当我们切换到Right组件时候,Right组件会缓存着,这样我们切换回来,Left组件的操作还在着:

image-20220720161826236

# 1.2.2 运行在vue的哪个生命周期?

  • 当组件第一次被创建的时候,既会执行 created 生命周期,也会执行 activated 生命周期
  • 当组件被激活的时候,只会触发 activated 生命周期,不再触发 created。因为组件没有被重新创建
<script>
export default {
  name: 'MyLeft',
  data() {
    return {
      count: 0
    }
  },
  created() {
    console.log('Left 组件被创建了!')
  },
  destroyed() {
    console.log('Left 组件被销毁了~~~')
  },

  // 当组件第一次被创建的时候,既会执行 created 生命周期,也会执行 activated 生命周期
  // 组件被激活的时候,只会触发 activated 生命周期,不再触发 created。因为组件没有被重新创建
  activated() {
    console.log('组件被激活了,activated')
  },
  deactivated() {
    console.log('组件被缓存了,deactivated')
  }
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

(1)当组件第一次被创建的时候,既会执行 created 生命周期,也会执行 activated 生命周期:

image-20220720162517850

(2)当组件被激活的时候,只会触发 activated 生命周期,不再触发 created。因为组件没有被重新创建:

image-20220720162557624

# 1.2.3 组件的注册名称和name名称

如果在“声明组件”的时候,没有为组件指定 name 名称,则组件的名称默认就是“注册时候的名称”

components: {
    // 如果在“声明组件”的时候,没有为组件指定 name 名称,则组件的名称默认就是“注册时候的名称”
    Left,
    Right
  }
1
2
3
4
5

image-20220720162857075

如果给组件一个name名,那么在调试的时候,和keep-alive指定名字的时候就要使用这个name名。

一般在开发都会给组件一个name名,注册名只是在使用组件时候使用一下。

export default {
  name: 'MyLeft',
  }

<keep-alive exclude="MyRight">
      <component :is="comName"></component>
</keep-alive>
1
2
3
4
5
6
7

image-20220720162857075

Last Updated: 9/7/2022, 11:32:53 PM