插槽slot和作用域插槽scoped slots

170 阅读1分钟
  • elementUI为例

slot

子组件使用slot标签占一个坑,父组件在使用这个子组件的时候可以在子组件标签中插入一些内容

*按钮

子组件:

    <el-button
      type="success"
      icon="el-icon-search"
    >
      <slot></slot>
    </el-button>

父组件:

    <my-button>
      <span>按钮</按钮>
    </my-button>

效果:

image.png

scoped slots

可以理解为使用slot-scope属性可以传递子组件数据到父组件

*级联选择器cascader自定义节点内容

子组件:(通过属性传递data、node)

    <el-cascader
      ......>
        <template slot-scope="{ node, data }">
          <slot :data="data" :node="node"></slot>
        </template>
    </el-cascader>

父组件:(slot-scope读取子组件作用域数值)

    <my-cascader>
      <template slot-scope="scope">
        <span>{{ scope.data.label }}</span>
        <span v-if="!scope.node.isLeaf"> ({{ scope.data.children.length }}) </span>
      </template>
    </my-cascader>

效果:

image.png