vue slot的一点理解(1)

先来一个实例,方便解释:
子组件:

<template>
  <div>
    <button></button>
    <slot>这里是默认值</slot>

    <slot name="one">这里是默认值one</slot>

    <slot name="two">这里是默认值two</slot>

    <slot name="three">这里是默认值three</slot>

    <slot name="dongdong" :value1="child1">这里是默认值1</slot>
  </div>
</template>

父组件:

<template>
  <div>
    <p>这里是普通插槽,一个组件中只能有一个这种插槽</p>
    <etbutton>{{ favalue }}</etbutton>

    <p>这里是具名插槽,这里的v-slot可以简写为#one</p>
    <etbutton>
      <template>这里是插入到默认插槽的内容</template>
      <template #one>这里是插入到one插槽的内容</template>
      <template v-slot:two>这里是插入到two插槽的内容</template>
      <template v-slot:three>这里是插入到three插槽的内容</template>
    </etbutton>

    <p>这里是作用域插槽</p>
    <!-- 作用域插槽的实现步骤如下:
    1.首先在子组件的的slot上面绑定一个值(:key = value)
    2.然后在父组件中使用v-slot:name=变量,吧slot的值存到这变量中
     -->
    <etbutton>
      <template v-slot:dongdong="slotdongdongval">{{
        slotdongdongval.value1
      }}</template>
    </etbutton>
  </div>
</template>

1.可以看到etbutton组件,相对父组件,他是一个子元素
2.其实,etbutton中的slot,他被当做etbutton组件的子元素
在vue渲染etbutton的时候,发现他不是一个常规的标签,认定他是一个组件之后,就会当做一个组件去解析。
父组件的vnode类似这样:

{

    tag:'div',

    children:[

       {
          tag:'test',
          children:['我是放在组件的 slot 11'] 
       }
    ]
}

当自定义组件渲染时候

if(如果是组件){
1initInternalComponent (vm, options);
}
initRender(vm);

走这里1initInternalComponent,然后吧test组件的插槽节点给了组件的选项的【_renderChildren】

function initInternalComponent(vm, options) {    



// 这个options是全局选项和组件设置选项的合集

    var opts = vm.$options = 

            Object.create(vm.constructor.options);  



    var componentOptions = parentVnode.componentOptions;



    // 传给组件选项_renderChildren

    opts._renderChildren = componentOptions.children;

}

源码我暂时研究不懂,知道有这么回事,不细说了。

注意一个过程:自定义组件,首先是需要实例初始化,然后用组件的模板(我理解就是vue文件吧),
去构建他的渲染函数。
什么是渲染函数:

with(this) {
    return _c('main', [
        "我在子组件里面", 
        _t("default")
    ], 2)
}

image

posted @ 2022-11-08 17:13  皮皮买  阅读(38)  评论(0编辑  收藏  举报