vue3 基础知识 (动态组件 keep-alive 等) 03

嘿,happy

文章目录


一、动态组件

动态组件是使用 component 组件,通过一个特殊的属性 is 来实现

  1. 一定是注册好的组件
  2. 我们需要将属性和监听事件放到 component 上来使用
javascript 复制代码
<template>
  <div>
    <button v-for="tab in tabs" 
            :key="tab"
            :class="{active: currentTab === tab}"
            @click="tabClick(tab)">
      {{tab}}
    </button>

    <component :is="currentTab"/>
  </div>
</template>

<script>
  import Home from "./pages/Home.vue";
  import About from "./pages/About.vue";
  import Category from "./pages/Category.vue";

  export default {
    components: {
      Home, About, Category
    },
    data() {
      return {
        tabs: ["home", "about", "category"],
        currentTab: "home"
      }
    },
    methods: {
      tabClick(tab) {
        this.currentTab = tab;
      },
    }
  }
</script>

<style scoped>
  .active {
    color: red;
  }
</style>

二、keep-alive

  • keep-alive 是 Vue 的内置组件,当它包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。
  • 和 transition 相似,keep-alive 是一个抽象组件:它自身不会渲染成一个 DOM 元素,也不会出现在父组件链中。

作用: 在组件切换过程中将状态保留在内存中,防止重复渲染DOM,减少加载时间及性能消耗,提高用户体验性。

原理:

在 created 函数调用时将需要缓存的 VNode 节点保存在 this.cache 中/在 render(页面渲染) 时,如果 VNode 的 name 符合缓存条件(可以用 include 以及 exclude 控制),则会从 this.cache 中取出之前缓存的 VNode 实例进行渲染。

keep-alive有一些属性 :

  1. include 只有 名称匹配的组件会被缓存
  2. exclude 任何名称匹配的组件都不会被缓存
  3. max 最多可以缓存多少组件实例,一旦达到这个数字,那么缓存组件中最近没有被访问的实例会被销毁;
  4. include 和 exclude prop 允许组件有条件地缓存

二者都可以用逗号分隔字符串、正则表达式或一个数组来表示

  • 匹配首先检查组件自身的 name 选项;
  • 如果 name 选项不可用,则匹配它的局部注册名称 (父组件 components 选项的键值)
javascript 复制代码
 // 逗号分隔字符串
<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>

// regex (使用 `v-bind`) -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>

// Array (使用 `v-bind`) 
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive>
相关推荐
灵感__idea3 小时前
Hello 算法:“走一步看一步”的智慧
前端·javascript·算法
吴文周5 小时前
告别重复劳动:一套插件让 AI 替你写代码、修Bug、做测试、上生产
前端·后端·ai编程
Mh5 小时前
我决定写一个 3D 地球仪来记录下我要去的地方
前端·javascript·动效
yaoxin5211236 小时前
390. Java IO API - WatchDir 示例
java·前端·python
懒狗小前端6 小时前
做了一个 codex 的中文文档网站,做的不好可以随便喷
前端·后端
. . . . .7 小时前
ref、useRef 和 forwardRef
前端·javascript·react.js
energy_DT7 小时前
2026年海上钻井平台数字孪生平台:引领海洋能源数字化转型
前端
Eric_见嘉7 小时前
在职前端 Agent 配置分享
前端·后端·agent
柚子8167 小时前
break跳出语句块的神奇技巧
前端·javascript
ejinxian9 小时前
Rust GUI框架Azul与Electron、WebView2
前端·javascript·electron