vue框架之slot与slot-scope及其做用域

前言: slot和slot-scope属于vue的高阶特性, 主要用于在自定义组件内插入原生的HTML元素,如:vue

<my-component>
    <div>自定义组件内插入原生HTML元素</div>
</my-component>复制代码

1 . slotbash

首先声明一个子组件:app

### Item.vue
<template>
  <div>
    <h3>子组件标题</h3>
    <slot name="header"></slot>
    <slot name="footer"></slot>
  </div>
</template>

<script>
  export default {
    data() {
        return {
            value: 456
        }
    }
  }
</script>复制代码

### App.vue (父组件或者根组件)
<template>
  <div class="app">
    <h2>父组件标题</h2>
    <item>
        <p slot="header">this is header slot---header: {{value}}</p>
        <p slot="footer">this is footer slot --footer: {{value}}</p>
    </item>
  </div>
</template>

<script>
  import Item from './Item.vue'

  export default {
    name: 'app',
    data () {
        return {
            value: 123
        }     
    }
    components: {
      Item
    }
  }
</script>复制代码

从测试可得,此时测试

header和footer的value均为123而非456,由于使用了当前组件App而非子组件Item的做用域复制代码

如要显示子组件Item内做用域的value,需设置slot-scope属性,以下:ui

### Item.vue
<template>
  <div>
    <h3>子组件标题</h3>
    <slot name="header" :value="value" a="bcd"></slot>
    <slot name="footer"></slot>
  </div>
</template>

<script>
  export default {
    data() {
        return {
            value: 456
        }
    }
  }
</script>复制代码

### App.vue (父组件或者根组件)
<template>
  <div class="app">
    <h2>父组件标题</h2>
    <item>
        <p slot="header" slot-scope="props">
            this is header slot---header: {{value}}    // 此处value仍是123
            item value: {{props.value}}                // 该处value返回456
            props返回一个对象: {{props}}                // { "value": 456, "a": "abc" }
        </p>
        <p slot="footer">this is footer slot --footer: {{value}}</p>
    </item>
  </div>
</template>复制代码

总结: this

1 . 使用slot能够在自定义组件内插入原生HTML元素,须要搭配使用name和slot属性,不然多个slot可能会返回重复的HTML元素。spa

2 . 使用slot-scope能够将slot内部的做用域指向该子组件,不然默认做用域指向调用slot的父组件。code