美文网首页
简单看一下普通插槽slot

简单看一下普通插槽slot

作者: HelenYin | 来源:发表于2021-03-23 16:23 被阅读0次

先看普通插槽
这里我仍然不看编译,直接用render函数来写slot,用下面这个例子

    // 子组件
    const AppLayout = {
      render(h) {
        return h('div', {}, [
          h('header', {}, [this.$slots.header]),
          h('main', {}, [this.$slots.default]),
          h('footer', {}, [this.$slots.footer]),
        ]);
      }
    };
    // 父组件
    new Vue({
      el: '#app',
      data() {
        return {
          title: '我是标题',
          msg: '我是内容',
          desc: '其它信息'
        }
      },
      render(h) {
        return h('div', {}, [
          h(AppLayout, {}, [
            h('h1', { slot: 'header' }, this.title),
            h('p', { slot: 'default' }, this.msg),
            h('p', { slot: 'footer' }, this.desc),
          ])
        ]);
      },
    });

首先我直接执行肯定会报错,因为到目前为止我还没有实现this.$slots。那么这里需要实现的就是把slot赋值给this.$slots
首先需要知道,slot本质上就是vnode,this.$slot存储的就是vnode。

这里我仍然把用户写的slot,放在Component 的 children中。我们在子组件实例化的时候,遍历children,如果child的data中有slot属性,就把它赋值给$slot。那么父组件里把子组件的vnode引用一下,在initInternalComponent函数里来做。parentVnode.componentOptions.children就是。
在initInternalComponent里做了这个赋值之后,接下来在initRender里来把$slots搞定一下。

export function initRender (vm) {
+  if (vm.$options._renderChildren) {
+    vm.$slots = resolveSlots(vm.$options._renderChildren, vm);
+  }
  vm.$createElement = (tag, data, children) => createElement(tag, data, children, vm);
}
function resolveSlots (chidren, vm) {
  const slot = {};
  for (const child of chidren) {
    if (child.data.slot) {
      slot[child.data.slot] = [child];
    }
  }
  return slot;
}

代码实现还是在这个仓库
https://github.com/TingYinHelen/tempo

相关文章

  • 简单看一下普通插槽slot

    先看普通插槽这里我仍然不看编译,直接用render函数来写slot,用下面这个例子 首先我直接执行肯定会报错,因为...

  • vue2.6.0版本插槽的使用

    插槽slot简单的理解就是一段html代码模板,只是需要的在一个特定的情况下使用。插槽分为普通插槽,具名插槽,作用...

  • 插槽

    默认插槽: 具名插槽:slot name='footer' 作用域插槽:v-slot===slot-scope 默...

  • 2-6 vue 匿名插槽-slot

    匿名插槽-slot Slot插槽 —— 实现内容分发 什么是slot?slot的意思是插槽,其目的在于让组件的可扩...

  • Vue之深入理解插槽—slot, slot-scope, v-s

    Vue 2.6.0 以前Vue 2.6.0 以后具名插槽 slot具名插槽 v-slot作用域插槽 slot-sc...

  • 插槽、rem适配

    一、插槽slot 普通插槽 子组件 具名插槽(有名字的插槽) 子组件 二、rem适配 一、rem与px 的换算计算...

  • vue 插槽的使用

    vue 插槽手册 深入理解vue中的slot与slot-scope 插槽的使用其实是很简单首先要明白插槽是使用在子...

  • 插槽

    插槽的基础使用,

  • 插槽slot

    插槽,占位符slot具名插槽,指定占位符slot、name作用域插槽,子组件占位符向父组件占位符通信。slot、s...

  • vue slot匿名插槽 / 具名插槽 / 作用域插槽

    slot 匿名插槽 slot 具名插槽 应用场景 slot 作用域插槽: 在父组件中可以获得子组件的数据,并在父组...

网友评论

      本文标题:简单看一下普通插槽slot

      本文链接:https://www.haomeiwen.com/subject/hmgxhltx.html