Slot使用

slot 的简单使用

为什么要使用slot?

如果项目中需要一个模态框提示 付款成功,付款失败。那么这个模态框也就仅仅差这几个字或者是状态图片而已。那么此时应用solt就是一个非常不错的选择,说白了就是,在使用相同组件的时候可以通过slot了展现不同的效果。

单个 slot

下面是一个没有加入 slot 的 例子

<template>
  <children>父组件的内容</children>
</template>
<script>
  const children = {
    template: `
这里是子组件
`
} export default { name: "test", components: { children } } </script>

Slot使用_第1张图片

可以看到 我们在 children 组件中加入了一段话,但是班没有显示出来,因为 子组件中 没有放置我们在 父组件 中的文字的 位置,所以我们需要改动一下

加入slot 效果

<template>
  <children>父组件的内容</children>
</template>
<script>
  const children = {
    template: `
这里是子组件
`
// 我们在 子组件里面加入了一个 slot 标签 } export default { name: "test", components: { children } } </script>

Slot使用_第2张图片

这里的效果是很明显,我们在父组件里面添加的文字被 正常的显示出来

具名slot

上面是当组件的模板中有一个slot的情况,那么一个组件中如果想使用多个slot那么此时就应该使用具名slot。

slot 元素可以用一个特殊的属性 name 来配置如何分发内容。多个 slot 可以有不同的名字。具名 slot 将匹配内容片段中有对应 slot 特性的元素。

仍然可以有一个匿名 slot ,它是默认 slot ,作为找不到匹配的内容片段的备用插槽。如果没有默认的 slot ,这些找不到匹配的内容片段将被抛弃。

<template>
  <children>
    <div slot="header">父组件添加的头部</div>
    <div>这里是默认的slot的内容</div>
    <div slot="footer">父组件添加的底部</div>
  </children>
</template>
<script>
  const children = {
    template: `
这是子组件默认的信息
`
} export default { name: "test", data() { return {} }, components: { children } } </script>

Slot使用_第3张图片

很简单是吧,下面来看看 作用域插槽

作用域插槽

作用域插槽的数据由父组件决定,内容却由子组件控制。简单来说:作用域插槽是一个带绑定数据的插槽

调用父组件数据

<template>
  <children :items="items">
    <template scope="variable"> <!-- 作用域插槽也是可以具名的 -->
      <li style="padding: 5px;">{{variable.el}}</li><!-- scope变量调用的值必须和slot传出的值保持一致 -->
    </template>
  </children>
</template>
<script>
  const children = {
    template: `
`
, props: ['items'] } export default { name: "test", data() { return { items: [ { name: '我' }, { name: '是' }, { name: '江' }, { name: '小' }, { name: '白' } ] } }, components: { children } } </script> <style scoped></style>

Slot使用_第4张图片

调用子组件数据

<template>
  <children>
    <ul slot-scope="data">
      <li v-for="(item, index) in data.data" :key="index">{{item.name}}</li>
    </ul>
  </children>
</template>
<script>
  const children = {
    template: `
`
, data: function () { return { items: [ { name: '我' }, { name: '是' }, { name: '江' }, { name: '小' }, { name: '白' } ] } } } export default { name: "test", data() { return {} }, components: { children } } </script> <style scoped></style>

Slot使用_第5张图片

最后贴一个基于 iview 的Modal组件的使用示例

iview Modal 示例

你可能感兴趣的:(vue)