15. Vue内置的组件

129 阅读3分钟

1. component——渲染一个“元组件”为动态组件

  • Props

    • is - string | ComponentDefinition | ComponentConstructor
    • inline-template - boolean
  • 用法

    渲染一个“元组件”为动态组件。依 is 的值,来决定哪个组件被渲染。

    <!-- 动态组件由 vm 实例的 `componentId` property 控制 -->
    <component :is="componentId"></component><!-- 也能够渲染注册过的组件或 prop 传入的组件 -->
    <component :is="$options.components.child"></component>
    
  • 参考动态组件

    image.png

2. transition——把过渡效果应用到其包裹的内容上

  • Props

    • name - string,用于自动生成 CSS 过渡类名。例如:name: 'fade' 将自动拓展为 .fade-enter.fade-enter-active 等。默认类名为 "v"
    • appear - boolean,是否在初始渲染时使用过渡。默认为 false
    • css - boolean,是否使用 CSS 过渡类。默认为 true。如果设置为 false,将只通过组件事件触发注册的 JavaScript 钩子。
    • type - string,指定过渡事件类型,侦听过渡何时结束。有效值为 "transition""animation"。默认 Vue.js 将自动检测出持续时间长的为过渡事件类型。
    • mode - string,控制离开/进入过渡的时间序列。有效的模式有 "out-in""in-out";默认同时进行。
    • duration - number | { enter: number, leave: number } 指定过渡的持续时间。默认情况下,Vue 会等待过渡所在根元素的第一个 transitionendanimationend 事件。
    • enter-class - string
    • leave-class - string
    • appear-class - string
    • enter-to-class - string
    • leave-to-class - string
    • appear-to-class - string
    • enter-active-class - string
    • leave-active-class - string
    • appear-active-class - string
  • 事件

    • before-enter
    • before-leave
    • before-appear
    • enter
    • leave
    • appear
    • after-enter
    • after-leave
    • after-appear
    • enter-cancelled
    • leave-cancelled (v-show only)
    • appear-cancelled
  • 用法

    <transition> 元素作为单个元素/组件的过渡效果。<transition> 只会把过渡效果应用到其包裹的内容上,而不会额外渲染 DOM 元素,也不会出现在可被检查的组件层级中

    <!-- 简单元素 -->
    <transition>
      <div v-if="ok">toggled content</div>
    </transition><!-- 动态组件 -->
    <transition name="fade" mode="out-in" appear>
      <component :is="view"></component>
    </transition><!-- 事件钩子 -->
    <div id="transition-demo">
      <transition @after-enter="transitionComplete">
        <div v-show="ok">toggled content</div>
      </transition>
    </div>
    
    new Vue({
      ...
      methods: {
        transitionComplete: function (el) {
          // 传入 'el' 这个 DOM 元素作为参数。
        }
      }
      ...
    }).$mount('#transition-demo')
    

    image.png

  • 参考过渡:进入,离开和列表

    image.png

    // node_modules\vue\src\platforms\web\runtime\components\transition.js
    export default {
      name: 'transition',
      props: transitionProps,//如上图
      abstract: true,
    
      render (h: Function) {
        let children: any = this.$slots.default
        if (!children) {
          return
        }
    
        // filter out text nodes (possible whitespaces)
        children = children.filter(isNotTextNode)
        /* istanbul ignore if */
        if (!children.length) {
          return
        }
    
        // warn multiple elements
        if (process.env.NODE_ENV !== 'production' && children.length > 1) {
          warn(
            '<transition> can only be used on a single element. Use ' +
            '<transition-group> for lists.',
            this.$parent
          )
        }
    
        const mode: string = this.mode
    
        // warn invalid mode
        if (process.env.NODE_ENV !== 'production' &&
          mode && mode !== 'in-out' && mode !== 'out-in'
        ) {
          warn(
            'invalid <transition> mode: ' + mode,
            this.$parent
          )
        }
    
        const rawChild: VNode = children[0]
    
        // if this is a component root node and the component's
        // parent container node also has transition, skip.
        if (hasParentTransition(this.$vnode)) {
          return rawChild
        }
    
        // apply transition data to child
        // use getRealChild() to ignore abstract components e.g. keep-alive
        const child: ?VNode = getRealChild(rawChild)
        /* istanbul ignore if */
        if (!child) {
          return rawChild
        }
    
        if (this._leaving) {
          return placeholder(h, rawChild)
        }
    
        // ensure a key that is unique to the vnode type and to this transition
        // component instance. This key will be used to remove pending leaving nodes
        // during entering.
        const id: string = `__transition-${this._uid}-`
        child.key = child.key == null
          ? child.isComment
            ? id + 'comment'
            : id + child.tag
          : isPrimitive(child.key)
            ? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key)
            : child.key
    
        const data: Object = (child.data || (child.data = {})).transition = extractTransitionData(this)
        const oldRawChild: VNode = this._vnode
        const oldChild: VNode = getRealChild(oldRawChild)
    
        // mark v-show
        // so that the transition module can hand over the control to the directive
        if (child.data.directives && child.data.directives.some(isVShowDirective)) {
          child.data.show = true
        }
    
        if (
          oldChild &&
          oldChild.data &&
          !isSameChild(child, oldChild) &&
          !isAsyncPlaceholder(oldChild) &&
          // #6687 component root is a comment node
          !(oldChild.componentInstance && oldChild.componentInstance._vnode.isComment)
        ) {
          // replace old child transition data with fresh one
          // important for dynamic transitions!
          const oldData: Object = oldChild.data.transition = extend({}, data)
          // handle transition mode
          if (mode === 'out-in') {
            // return placeholder node and queue update when leave finishes
            this._leaving = true
            mergeVNodeHook(oldData, 'afterLeave', () => {
              this._leaving = false
              this.$forceUpdate()
            })
            return placeholder(h, rawChild)
          } else if (mode === 'in-out') {
            if (isAsyncPlaceholder(child)) {
              return oldRawChild
            }
            let delayedLeave
            const performLeave = () => { delayedLeave() }
            mergeVNodeHook(data, 'afterEnter', performLeave)
            mergeVNodeHook(data, 'enterCancelled', performLeave)
            mergeVNodeHook(oldData, 'delayLeave', leave => { delayedLeave = leave })
          }
        }
    
        return rawChild
      }
    }
    
    

    image.png

3.transition-group——为多个元素/组件提供过渡效果

  • Props

    • tag - string,默认为 span
    • move-class - 覆盖移动过渡期间应用的 CSS 类。
    • 除了 mode,其他 attribute 和 <transition> 相同。
  • 事件

    • 事件和 <transition> 相同。
  • 用法

    <transition-group> 元素作为多个元素/组件的过渡效果。<transition-group> 渲染一个真实的 DOM 元素。默认渲染 <span>,可以通过 tag attribute 配置哪个元素应该被渲染。

    注意,每个 <transition-group> 的子节点必须有独立的 key,动画才能正常工作

    <transition-group> 支持通过 CSS transform 过渡移动。当一个子节点被更新,从屏幕上的位置发生变化,它会被应用一个移动中的 CSS 类 (通过 name attribute 或配置 move-class attribute 自动生成)。如果 CSS transform property 是“可过渡”property,当应用移动类时,将会使用 FLIP 技术使元素流畅地到达动画终点。

    <transition-group tag="ul" name="slide">
      <li v-for="item in items" :key="item.id">
        {{ item.text }}
      </li>
    </transition-group>
    

    image.png

  • 参考过渡:进入,离开和列表

    image.png

4. keep-alive——缓存不活动的组件实例,而不是销毁它们

  • Props

    • include - 字符串或正则表达式。只有名称匹配的组件会被缓存。
    • exclude - 字符串或正则表达式。任何名称匹配的组件都不会被缓存。
    • max - 数字。最多可以缓存多少组件实例。
  • 用法

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

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

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

    主要用于保留组件状态或避免重新渲染。

    <!-- 基本 -->
    <keep-alive>
      <component :is="view"></component>
    </keep-alive><!-- 多个条件判断的子组件 -->
    <keep-alive>
      <comp-a v-if="a > 1"></comp-a>
      <comp-b v-else></comp-b>
    </keep-alive><!-- 和 `<transition>` 一起使用 -->
    <transition>
      <keep-alive>
        <component :is="view"></component>
      </keep-alive>
    </transition>
    

    注意,<keep-alive> 是用在其一个直属的子组件被开关的情形。如果你在其中有 v-for 则不会工作。如果有上述的多个条件性的子元素,<keep-alive> 要求同时只有一个子元素被渲染

  • include and exclude

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

    <!-- 逗号分隔字符串 -->
    <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>
    

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

  • max

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

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

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

  • 参考动态组件 - keep-alive

    image.png

5. slot——组件模板之中的内容插槽

  • Props

    • name - string,用于命名插槽。
  • Usage

    <slot> 元素作为组件模板之中的内容分发插槽。<slot> 元素自身将被替换。

    详细用法,请参考下面教程的链接。

  • 参考通过插槽分发内容

    image.png