组件插槽

插槽的作用

子组件的模板结构可以在调用时动态改变,扩展了组件使用的灵活性,只需要在组件的模板的对应位置加上 <slot> 组件就可以了,因此在 UI 框架中会经常使用。

子组件模板:

<template id="temp-child">
    <div>
        <h4>这是一个子组件</h4>
        <!-- slot 定义一个插槽,等待被插 -->
        <slot></slot>
        <!-- slot 组件也可以嵌套内容作为无插入内容时的结构 -->
        <slot><span>无内容插入<span></slot>
        <slot name="guanjie"></slot>
        <p>------华丽的分割线-------</p>
        <slot name="test" :test="msg"></slot>
    </div>
</template>
var child = {
  template: "#temp-child",
  data() {
    return {
      msg: "我也希望能够看看外面的世界!"
    };
  }
};

子组件的调用

<child>
  <ul>
    <li>没有绑定到规定名字的内容,默认会插入到子组件的所有匿名插槽内</li>
  </ul>
  <p slot="guanjie">我是子组件调用之间的标签</p>
  <!---作用域插槽-->
  <h1 slot="test" slot-scope="mySelf">{{mySelf.test}}</h1>
</child>
Last Updated:
Contributors: zerojs