组件切换与性能

  • Vue 会尽可能高效地渲染元素,通常会复用已有元素而不是从头开始渲染。这么做除了使 Vue 变得非常快之外,还有其它一些好处。例如,如果你允许用户在不同的登录方式之间切换,会保存input中用户的输入值。这种复用只对数据内容负责,例如渲染的数组被赋值替代,只要数组项相同就会被复用

component

  • 配合is,作为组件的容器
<component v-bind:is="view"></component>

new Vue({
  el: '#transition-components-demo',
  data: {
    view: 'v-a'
  },
  components: {
    'v-a': {
      template: '<div>Component A</div>'
    },
    'v-b': {
      template: '<div>Component B</div>'
    }
  }
})

is

  • 通过is切换组件,由于每次都会销毁和创建组件,导致选中的值或打开的标签页恢复初始值,我们可以用一个 <keep-alive> 缓存下来。缓存的组件切换时,它的 activated(激活) 和 deactivated(停用) 这两个生命周期钩子函数将会被对应执行。并且它要求同时只有一个子元素被渲染。
<!-- 失活的组件将会被缓存!-->
<keep-alive>
  <component v-bind:is="currentTabComponent"></component>
</keep-alive>
  • is可以改变任意元素包括原生,例如<li is="todo-item">

keep-alive

  • <transition> 和 <keep-alive> 两个结合一起用,要确保在内层使用 <keep-alive>
  • <keep-alive> 的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>

v-show

  • 如果需要非常频繁地切换,则使用 v-show 较好;
  • v-show 不支持 <template> 元素。

v-once

  • 组件包含了大量静态内容。在这种情况下,你可以在根元素上添加 v-once 特性以确保这些内容只计算一次然后缓存起来
Vue.component('terms-of-service', {
  template: `
    <div v-once>
      <h1>Terms of Service</h1>
      ... a lot of static content ...
    </div>
  `
})
原文地址:https://www.cnblogs.com/qq3279338858/p/10282102.html