Vue插槽的实现原理是什么

发布时间:2021-06-29 16:12:34 作者:chen
来源:亿速云 阅读:148

这篇文章主要介绍“Vue插槽的实现原理是什么”,在日常操作中,相信很多人在Vue插槽的实现原理是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Vue插槽的实现原理是什么”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

目录

一、样例代码

<!-- 子组件comA -->
<template>
  <div class='demo'>
    <slot><slot>
    <slot name='test'></slot>
    <slot name='scopedSlots' test='demo'></slot>
  </div>
</template>
<!-- 父组件 -->
<comA>
  <span>这是默认插槽</span>
  <template slot='test'>这是具名插槽</template>
  <template slot='scopedSlots' slot-scope='scope'>这是作用域插槽(老版){{scope.test}}</template>
  <template v-slot:scopedSlots='scopeProps' slot-scope='scope'>这是作用域插槽(新版){{scopeProps.test}}</template>
</comA>

二、透过现象看本质

插槽的作用是实现内容分发,实现内容分发,需要两个条件:

组件内部定义的slot标签,我们可以理解为占位符,父组件中插槽内容,就是要分发的内容。插槽处理本质就是将指定内容放到指定位置。废话不多说,从本篇文章中,将能了解到:

三、实现原理

vue组件实例化顺序为:父组件状态初始化(datacomputedwatch...) --> 模板编译 --> 生成render方法 --> 实例化渲染watcher --> 调用render方法,生成VNode --> patch VNode,转换为真实DOM --> 实例化子组件 --> ......重复相同的流程 --> 子组件生成的真实DOM挂载到父组件生成的真实DOM上,挂载到页面中 --> 移除旧节点

从上述流程中,可以推测出:

1.父组件模板解析在子组件之前,所以父组件首先会获取到插槽模板内容

2.子组件模板解析在后,所以在子组件调用render方法生成VNode时,可以借助部分手段,拿到插槽的VNode节点

3.作用域插槽可以获取子组件内变量,因此作用域插槽的VNode生成,是动态的,即需要实时传入子组件的作用域scope

整个插槽的处理阶段大致分为三步:

以下面代码为例,简要概述插槽运转的过程。

<div id='app'>
  <test>
    <template slot="hello">
      123
    </template>
  </test>
</div>
<script>
  new Vue({
    el: '#app',
    components: {
      test: {
        template: '<h2>' +
          '<slot name="hello"></slot>' +
          '</h2>'
      }
    }
  })
</script>

四、父组件编译阶段

编译是将模板文件解析成AST语法树,会将插槽template解析成如下数据结构:

{
  tag: 'test',
  scopedSlots: { // 作用域插槽
    // slotName: ASTNode,
    // ...
  }
  children: [
    {
      tag: 'template',
      // ...
      parent: parentASTNode,
      children: [ childASTNode ], // 插槽内容子节点,即文本节点123
      slotScope: undefined, // 作用域插槽绑定值
      slotTarget: "\"hello\"", // 具名插槽名称
      slotTargetDynamic: false // 是否是动态绑定插槽
      // ...
    }
  ]
}

五、父组件生成渲染方法

根据AST语法树,解析生成渲染方法字符串,最终父组件生成的结果如下所示,这个结构和我们直接写render方法一致,本质都是生成VNode, 只不过_chthis.$createElement的缩写。

with(this){
  return _c('div',{attrs:{"id":"app"}},
  [_c('test',
    [
      _c('template',{slot:"hello"},[_v("\n      123\n    ")])],2)
    ],
  1)
}

六、父组件生成VNode

调用render方法,生成VNode,VNode具体格式如下:

{
  tag: 'div',
  parent: undefined,
  data: { // 存储VNode配置项
    attrs: { id: '#app' }
  },
  context: componentContext, // 组件作用域
  elm: undefined, // 真实DOM元素
  children: [
    {
      tag: 'vue-component-1-test',
      children: undefined, // 组件为页面最小组成单元,插槽内容放放到子组件中解析
      parent: undefined,
      componentOptions: { // 组件配置项
        Ctor: VueComponentCtor, // 组件构造方法
        data: {
          hook: {
            init: fn, // 实例化组件调用方法
            insert: fn,
            prepatch: fn,
            destroy: fn
          },
          scopedSlots: { // 作用域插槽配置项,用于生成作用域插槽VNode
            slotName: slotFn
          }
        },
        children: [ // 组件插槽节点
          tag: 'template',
          propsData: undefined, // props参数
          listeners: undefined,
          data: {
            slot: 'hello'
          },
          children: [ VNode ],
          parent: undefined,
          context: componentContext // 父组件作用域
          // ...
        ] 
      }
    }
  ],
  // ...
}

vue中,组件是页面结构的基本单元,从上述的VNode中,我们也可以看出,VNode页面层级结构结束于test组件,test组件children处理会在子组件初始化过程中处理。子组件构造方法组装与属性合并在vue-dev\src\core\vdom\create-component.js createComponent方法中,组件实例化调用入口是在vue-dev\src\core\vdom\patch.js createComponent方法中。

七、子组件状态初始化

实例化子组件时,会在initRender -> resolveSlots方法中,将子组件插槽节点挂载到组件作用域vm中,挂载形式为vm.$slots = {slotName: [VNode]}形式。

八、子组件编译阶段

子组件在编译阶段,会将slot节点,编译成以下AST结构:

{
  tag: 'h2',
  parent: undefined,
  children: [
    {
      tag: 'slot',
      slotName: "\"hello\"",
      // ...
    }
  ],
  // ...
}

九、子组件生成渲染方法

生成的渲染方法如下,其中_trenderSlot方法的简写,从renderSlot方法,我们就可以直观的将插槽内容与插槽点联系在一起。

// 渲染方法
with(this){
  return _c('h2',[ _t("hello") ], 2)
}
// 源码路径:vue-dev\src\core\instance\render-helpers\render-slot.js
export function renderSlot (
  name: string,
  fallback: ?Array<VNode>,
  props: ?Object,
  bindObject: ?Object
): ?Array<VNode> {
  const scopedSlotFn = this.$scopedSlots[name]
  let nodes
  if (scopedSlotFn) { // scoped slot
    props = props || {}
    if (bindObject) {
      if (process.env.NODE_ENV !== 'production' && !isObject(bindObject)) {
        warn(
          'slot v-bind without argument expects an Object',
          this
        )
      }
      props = extend(extend({}, bindObject), props)
    }
    // 作用域插槽,获取插槽VNode
    nodes = scopedSlotFn(props) || fallback
  } else {
    // 获取插槽普通插槽VNode
    nodes = this.$slots[name] || fallback
  }

  const target = props && props.slot
  if (target) {
    return this.$createElement('template', { slot: target }, nodes)
  } else {
    return nodes
  }
}

作用域插槽与具名插槽区别

<!-- demo -->
<div id='app'>
  <test>
      <template slot="hello" slot-scope='scope'>
        {{scope.hello}}
      </template>
  </test>
</div>
<script>
    var vm = new Vue({
        el: '#app',
        components: {
            test: {
                data () {
                    return {
                        hello: '123'
                    }
                },
                template: '<h2>' +
                    '<slot name="hello" :hello="hello"></slot>' +
                  '</h2>'
            }
        }
    })

</script>

作用域插槽与普通插槽相比,主要区别在于插槽内容可以获取到子组件作用域变量。由于需要注入子组件变量,相比于具名插槽,作用域插槽有以下几点不同:

作用域插槽在组装渲染方法时,生成的是一个包含注入作用域的方法,相对于createElement生成VNode,多了一层注入作用域方法包裹,这也就决定插槽VNode作用域插槽是在子组件生成VNode时生成,而具名插槽是在父组件创建VNode时生成。_uresolveScopedSlots,其作用为将节点配置项转换为{scopedSlots: {slotName: fn}}形式。

with (this) {
        return _c('div', {
            attrs: {
                "id": "app"
            }
        }, [_c('test', {
            scopedSlots: _u([{
                key: "hello",
                fn: function(scope) {
                    return [_v("\n        " + _s(scope.hello) + "\n      ")]
                }
            }])
        })], 1)
    }

子组件初始化时会处理具名插槽节点,挂载到组件$slots中,作用域插槽则在renderSlot中直接被调用

除此之外,其他流程大致相同。插槽作用机制不难理解,关键还是模板解析与生成render函数这两步内容较多,流程较长,比较难理解。

十、使用技巧

通过以上解析,能大概了解插槽处理流程。工作中大部分都是用模板来编写vue代码,但是某些时候模板有一定的局限性,需要借助于render方法放大vue的组件抽象能力。那么在render方法中,我们插槽的使用方法如下:

10.1、具名插槽

插槽处理一般分为两块:

<div id='app'>
<!--  <test>-->
<!--    <template slot="hello">-->
<!--      123-->
<!--    </template>-->
<!--  </test>-->
</div>
<script>
  new Vue({
    // el: '#app',
    render (createElement) {
      return createElement('test', [
        createElement('h4', {
          slot: 'hello',
          domProps: {
            innerText: '123'
          }
        })
      ])
    },
    components: {
      test: {
        render(createElement) {
          return createElement('h2', [ this.$slots.hello ]);
        }
        // template: '<h2>' +
        //   '<slot name="hello"></slot>' +
        //   '</h2>'
      }
    }
  }).$mount('#app')
</script>

10.2、作用域插槽

作用域插槽使用比较灵活,可以注入子组件状态。作用域插槽 + render方法,对于二次组件封装作用非常大。举个栗子,在对ElementUI table组件进行基于JSON数据封装时,作用域插槽用处就非常大了。

<div id='app'>
<!--  <test>-->
<!--    <span slot="hello" slot-scope='scope'>-->
<!--      {{scope.hello}}-->
<!--    </span>-->
<!--  </test>-->
</div>
<script>
  new Vue({
    // el: '#app',
    render (createElement) {
      return createElement('test', {
        scopedSlots:{
          hello: scope => { // 父组件生成渲染方法中,最终转换的作用域插槽方法和这种写法一致
            return createElement('span', {
              domProps: {
                innerText: scope.hello
              }
            })
          }
        }
      })
    },
    components: {
      test: {
        data () {
          return {
            hello: '123'
          }
        },
        render (createElement) {
          // 作用域插槽父组件传递过来的是function,需要手动调用生成VNode
          let slotVnode = this.$scopedSlots.hello({ hello: this.hello })
          return createElement('h2', [ slotVnode ])
        }
        // template: '<h2>' +
        //   '<slot name="hello" :hello="hello"></slot>' +
        //   '</h2>'
      }
    }
  }).$mount('#app')

</script>

到此,关于“Vue插槽的实现原理是什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. Vue为什么要有插槽
  2. Vue实现原理是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue

上一篇:python中合赋值运算符的作用是什么

下一篇:Vue指令的实现原理介绍

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》