Vue动态组件 & keep-alive

前言

在 vue 中,实现 Tab 切换主要有三种方式:使用动态组件,使用 vue-router 路由,使用第三方插件。本文将详细介绍Vue动态组件。所谓动态组件就是让多个组件使用同一个挂载点,并动态切换。

一、is用法

通过使用保留的 <component> 元素,动态地绑定到它的 is 特性,我们让多个组件可以使用同一个挂载点,并动态切换。根据 v-bind:is="组件名" 中的组件名去自动匹配组件,如果匹配不到则不显示。改变挂载的组件,只需要修改is指令的值即可。

【1.1】动态绑定已注册组件的名字

<!DOCTYPE html>
<html>

<head>
  <title>Dynamic Components Example</title>
  <script src="https://unpkg.com/vue"></script>
</head>

<body>
  <div id="example">
    <button @click="change">切换页面</button>
    <component :is="currentView"></component>
  </div>

  <script>
    const home = {
      template: '<div>我是主页</div>'
    };
    const detail = {
      template: '<div>我是详情页</div>'
    };
    const archive = {
      template: '<div>我是存档页</div>'
    };
    new Vue({
      el: '#example',
      components: {
        home,
        detail,
        archive,
      },
      data: {
        index: 0,
        arr: ['home', 'detail', 'archive'],
      },
      computed: {
        currentView() {
          return this.arr[this.index];
        }
      },
      methods: {
        change() {
          this.index = (++this.index) % 3;
        }
      }
    })
  </script>
</body>

</html>

【1.2】直接绑定到组件对象上

<!DOCTYPE html>
<html>

<head>
  <title>Dynamic Components Example</title>
  <script src="https://unpkg.com/vue"></script>
</head>

<body>
  <div id="example">
    <button @click="change">切换页面</button>
    <component :is="currentView"></component>
  </div>

  <script>
    new Vue({
      el: '#example',
      data: {
        index: 0,
        arr: [{
          template: `<div>我是主页</div>`
        }, {
          template: `<div>我是详情页</div>`
        }, {
          template: `<div>我是存档页</div>`
        }],
      },
      computed: {
        currentView() {
          return this.arr[this.index];
        }
      },
      methods: {
        change() {
          this.index = (++this.index) % 3;
        }
      }
    })
  </script>
</body>

</html>

二、keep-alive缓存

上面我们已经实现通过绑定is来切换不同的组件,被切换掉的组件(非当前显示组件),是直接被移除了。假如需要子组件在切换后,依然保留在内存中,保留它的状态或避免下次出现的时候重新渲染。那么就应该使用<keep-alive>包裹组件,<keep-alive>是一个抽象组件,它自身不会渲染一个DOM元素,也不会出现在父组件链中,当<keep-alive>包裹组件时,会缓存不活动的组件实例,而不是销毁它们。

【2.1】基础用法

 <div id="example">
    <button @click="change">切换页面</button>
    <keep-alive>
      <component :is="currentView"></component>
    </keep-alive>
  </div>

【2.2】条件判断

如果有多个条件性的子组件,<keep-alive> 要求同时只有一个子组件被渲染

  <div id="example">
    <button @click="change">切换页面</button>
    <keep-alive>
      <Home v-if="index==0" />
      <Detail v-else-if="index==1" />
      <Archive v-else />
    </keep-alive>
  </div>

【2.3】activated 和 deactivated

在 2.2.0 及其更高版本中,activated 和 deactivated 将会在<keep-alive> 树内的所有嵌套组件中触发。

当组件在<keep-alive>  内被切换,它的 activated 和 deactivated 这两个生命周期钩子函数将会被对应执行。

<!DOCTYPE html>
<html>

<head>
  <title>Dynamic Components Example</title>
  <script src="https://unpkg.com/vue"></script>
</head>

<body>
  <div id="example">
    <button @click="change">切换页面</button>
    <keep-alive>
      <component :is="currentView" @pass-data="getData"></component>
    </keep-alive>
    <p>{{msg}}</p>
  </div>

  <script>
    new Vue({
      el: '#example',
      data: {
        index: 0,
        msg: '',
        arr: [{
          template: `<div>我是主页</div>`,
          activated() {
            this.$emit('pass-data', '主页被添加');
          },
          deactivated() {
            this.$emit('pass-data', '主页被移除');
          },
        }, {
          template: `<div>我是详情页</div>`
        }, {
          template: `<div>我是存档页</div>`
        }],
      },
      computed: {
        currentView() {
          return this.arr[this.index];
        }
      },
      methods: {
        change() {
          var len = this.arr.length;
          this.index = (++this.index) % len;
        },
        getData(value) {
          this.msg = value;
          setTimeout(() => {
            this.msg = '';
          }, 500)
        }
      }
    })
  </script>
</body>

</html>

【2.4】props

① include: 字符串或正则表达式,只有名称匹配的组件会被缓存。

② exclude: 字符串或正则表达式,任何名称匹配的组件都不会被缓存。

③ max: 数字,最多可以缓存多少组件实例。

include和 exclude 允许组件有条件地缓存。二者都可以用逗号分隔字符串、正则表达式或一个数组来表示。

匹配首先检查组件自身的 name 选项,如果 name 选项不可用,则匹配它的局部注册名称 (父组件 components 选项的键值)。匿名组件不能被匹配。

<!-- 逗号分隔字符串 -->
<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>

<!-- 正则表达式 (使用 `v-bind`) -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>

<!-- 数组 (使用 `v-bind`) -->
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive>

max 最多可以缓存多少组件实例。一旦这个数字达到了,在新实例被创建之前,已缓存组件中最久没有被访问的实例会被销毁掉。

<keep-alive :max="10">
  <component :is="view"></component>
</keep-alive>

【2.5】注意

<keep-alive> 不会在函数式组件中正常工作,因为它们没有缓存实例。

 

文章每周持续更新,可以微信搜索「 前端大集锦 」第一时间阅读,回复【视频】【书籍】领取200G视频资料和30本PDF书籍资料

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@Demi

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值