blog icon indicating copy to clipboard operation
blog copied to clipboard

vue中的slot与slot-scope总结

Open ly2011 opened this issue 7 years ago • 0 comments

插槽的分类

  • 默认插槽
  • 具名插槽
  • 作用域插槽

具名插槽

Vue中给我们提供了方法,我们一次可以使用很多插槽,然后给每一个插槽起个名字,也就是给我们的 <slot> 添加一个 name 属性。

<!--对话框组件(子组件)-->
<div class="dialog-panel">
  <slot name="header"></slot>
  <slot name="content"></slot>
  <slot name="footer"></slot>
</div>

在外部使用时,只需要提供对应名称, 我们就可以渲染出我们需要的:

<dialog-panel>
  <template slot="header">
    <div class="dialog-header">
      <h3 class="title">带名字的插槽</h3>
      <button class="close">x</button>
    </div>
  </template>
  <template slot="content">
    <div class="dialog-content">这是一个标准的 dialog 对话框</div>
  </template>
  <template slot="footer">
    <div class="dialog-footer">
      <el-button type="primary" plain>取消</el-button>
      <el-button type="primary">确定</el-button>
    </div>
  </template>
</dialog-panel>

具名插槽不仅仅只能用在

<div slot="header" class="dialog-header">
    <h3 class="title">带名字的插槽</h3>
    <button class="close">x</button>
</div>

作用域插槽

在Vue2.5+,slot-scope不在限制在

如果用一句话来描述作用域的话:它让我们在父组件中访问子组件的数据,就像利用props属性让子组件访问父组件的数据一样

<template>
  <div class="list-box">
    <h1>{{title}}</h1>
    <ul>
      <li v-for="(item, index) in list" :key="index">
        <slot :item="item"></slot>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  name: "List",
  props: {
    title: String,
    list: Array
  }
};
</script>

在父组件中使用:

<template>
  <div class="tirp-wrapper">
    <list title="酒店列表" :list="list">
      <span slot-scope="props">
        {{props.item.name}}
      </span>
    </list>
  </div>
</template>
<script>
import List from "./List";
export default {
  name: "Trip",
  components: { List },
  data() {
    return {
      list: [{
        name: "四季度假村酒店"
      },{
        name: "布宜诺斯艾利斯四季酒店"
      },{
        name: "孟买四季酒店"
      },{
        name: "新加坡四季酒店"
      }]
    };
  }
};
</script>

参考文档

  1. Vue一个案例引发「内容分发slot」的最全总结
  2. 深入理解vue中的slot与slot-scope

ly2011 avatar Nov 22 '18 01:11 ly2011