18、Vue 3 (2024 版)基础笔记 - 动态组件与 keep-alive 组件缓存

作者: 温新

图书: 【Vue 3 setup 使用实记】

阅读: 79

时间: 2024-05-19 01:28:26

动态组件

动态的组件的使用:

  • <component :is='组件名称' />
1、定义第一个组件

src/components/ButtonLeftDemo.vue

<template>
    <button>按钮 1</button>
</template>

<script setup lang="ts">

</script>

<style scoped>
    button {
        all: unset;
        background-color: green;
        padding: 20px 40px;
        color: white;
        border-radius: 10px;
    }
</style>
2、定义第二个组件

src/components/ButtonRightDemo.vue

<template>
    <button>按钮 2</button>
</template>

<script setup lang="ts">

</script>

<style scoped>
    button {
        all: unset;
        background-color: red;
        padding: 20px 40px;
        color: white;
        border-radius: 10px;
    }
</style>
3、使用组件切换

src/App.vue

<template>
    <div>
        <button @click="show = !show">切换组件</button>
    </div>
    <!-- 步骤三:组件切换 -->
    <component :is="show ? ButtonLeftDemo : ButtonRightDemo" />
</template>

<script setup lang="ts">
    import { ref } from 'vue';

    // 步骤一:引入组件
    import ButtonLeftDemo from './components/ButtonLeftDemo.vue';
    import ButtonRightDemo from './components/ButtonRightDemo.vue';

    // 步骤二:定义变量
    const show = ref(true)
</script>

keep-alive 组件缓存

组件缓存,我们基于上面的案例进行改造。

为什么要使用动态组件,先来看看效果。

1、改造组件

src/components/ButtonLeftDemo.vue

<template>
    <p>
        用户名:<input type="text">
    </p>
</template>

<script setup lang="ts">

</script>

<style scoped>
    button {
        all: unset;
        background-color: green;
        padding: 20px 40px;
        color: white;
        border-radius: 10px;
    }
</style>

src/components/ButtonRightDemo.vue

<template>
    <p>
        邮箱:<input type="text">
    </p>
</template>

<script setup lang="ts">

</script>

<style scoped>
    button {
        all: unset;
        background-color: red;
        padding: 20px 40px;
        color: white;
        border-radius: 10px;
    }
</style>
2、效果演示:不使用组件缓存

步骤一:输入用户名

步骤二:点击 切换组件,切换到邮箱

步骤三:输入邮箱

步骤四:再次点击切换组件,切换到用户名,发现刚刚输入的用户名有了

3、使用组件缓存

src/App.vue

<template>
    <div>
        <button @click="show = !show">切换组件</button>
    </div>
    <!-- 使用 keep-alive 实现组件缓存 -->
    <keep-alive>
        <component :is="show ? ButtonLeftDemo : ButtonRightDemo" />
    </keep-alive>
</template>

<script setup lang="ts">
    import { ref } from 'vue';

    import ButtonLeftDemo from './components/ButtonLeftDemo.vue';
    import ButtonRightDemo from './components/ButtonRightDemo.vue';

    const show = ref(true)
</script>
4、组件缓存效果演示

重复 2 中的操作,发现刚刚输入的信息还在,这就是组件缓存。

请登录后再评论