插槽新旧语法对比

184 阅读1分钟

插槽新旧语法对比

vue2.6之前

slot='插槽名' slot-scope="子组件传递过来的数据对象"

#插槽名="子组件传递过来的数据对象"

一、匿名插槽

子组件child

<div class="child">
    <!-- 子组件 -->
    <slot></slot>
</div>

父组件

  <div class="father">
    <!-- 父组件 -->
    <child>你好,插槽</child>
  </div>
<div class="father">
    <!-- 父组件 -->
    <child>
      <template> 你好,插槽 </template>
    </child>
  </div>

最后呈现的自组件的样子

<div>你好,插槽</div>

二、具名插槽

旧语法(vue2.6之前的)

子组件

 <div class="child">
    <!-- 子组件 -->
    <!-- <slot></slot> -->
    <slot name="center"></slot>
  </div>

父组件

<div class="father">
    <!-- 父组件 -->
    <child>
        <!-- 匿名插槽的名字默认是default -->
        <template slot="default">
            默认插槽中的内容
        </template>
        <!-- <template> 你好,插槽 </template> -->
        <template slot="center"> 你好,具名插槽 </template>
    </child>
</div>

呈现出来的效果

就是父组件template中的内容

新语法

子组件

  <div class="child">
    <!-- 子组件 -->
    <!-- <slot></slot> -->
    <slot name="center"></slot>
  </div>

父组件

<div class="father">
    <!-- 父组件 -->
    <child>
        <!-- <template v-slot:center> 具名插槽新语法 </template> -->
        <!-- 或者 -->
        <template #center>具名插槽新语法 简写写法</template>
    </child>
</div>

作用域插槽

旧语法(vue2.6之前的)

子组件

 <div class="child">
    <!-- 子组件 -->
    <!-- <slot></slot> -->
    <slot name="center" :id="123"></slot>
  </div>

父组件

 <div class="father">
    <!-- 父组件 -->
    <child>
      <template slot="center" slot-scope="scope">{{ scope }}</template>
    </child>
  </div>
  <div class="father">
    <!-- 父组件 -->
    <child>
      <!-- <template slot="center" slot-scope="scope">{{ scope }}</template> -->
      <!-- <template #center="scope">{{ scope }}</template> -->
      <p slot="center" slot-scope="scope">{{ scope.sex }}</p>
    </child>
  </div>

呈现的结果

{ "id": 123, "sex": "男" }

新语法

子组件

<div class="child">
    <!-- 子组件 -->
    <!-- <slot></slot> -->
    <slot name="center" :id="123" :sex="'男'"></slot>
</div>

父组件

  <div class="father">
    <!-- 父组件 -->
    <child>
      <!-- <template slot="center" slot-scope="scope">{{ scope }}</template> -->
      <template #center="scope">{{ scope }}</template>
    </child>
  </div>

呈现的效果

{ "id": 123, "sex": "男" }

也可以动态填写插槽名

<child>
    <template v-slot:[asdada]="{child:haizi}">
        {{haizi.name}}
    </template>
</child>

缩写

<child>
    <template #[asdada]="{child:haizi}">
        {{haizi.name}}
    </template>
</child>