v-slot

2019-06-22  本文已影响0人  皇甫圣坤

1、普通插槽

const com = {
  template: `
    <div>
      其他内容
      <slot></slot>
    </div>
  `
}
<div>
  <com>
    自定义内容
  </com>
</div>

2、具名插槽

默认的slot有一个名字为default

const com = {
  template: `
    <div>
      其他内容
      <slot name="自定义slot名字"></slot>
      <slot name="自定义slot名字2"></slot>
    </div>
  `
}
<div>
  <com>
    <template v-slot:自定义slot名字></template>
    <template v-slot:自定义slot名字2></template>
  </com>
</div>

2、作用域插槽

给用户留一些需要的数据

const com = {
  template: `
    <div>
      其他内容
      <slot key="value" key2="value2" key3="value3"></slot>
    </div>
  `
}
<div>
  <com>
    <template v-slot="scope">
      {{scope.key}}
      <button >删除</button>
    </template>
  </com>

  <com>
    <template v-slot="{key}"></template>
  </com>
</div>

如果被提供的内容只有一个默认插槽时,组件的标签可以直接被当做插槽的模板来使用<mo v-slot="slotProps">

// 根组件
<template>
    <div>
        <mo>
            <template v-slot:header="slotProps">
                <h1>{{slotProps.header + ' ' + msg}}</h1>
                
            </template>

            <p>A paragraph for the main content.</p>
            <p>And another one.</p>

            <template v-slot:footer>
                <p>Here's some contact info</p>
            </template>
        </mo>
    </div>
</template>

<script>
    import mo from './module.vue'
    export default {
        components: {
            mo
        },
        data() {
            return {
                msg: '这是根组件的消息'
            }
        }
    }
</script>

// 子组件
<template>
    <div>
        --header start--
        <header>
            <slot name="header" :header="header"></slot>
        </header>
        --header over--
        <div></div>
        --default start--
        <slot></slot>
        --default over--
        <div></div>
        --footer start--
        <footer>
            <slot name="footer"></slot>
        </footer>
        --dooter over--
    </div>
</template>

<script>
    export default {
        data() {
            return {
                header: '来自子组件的头部消息'
            }
        }
    }
</script>

<style scoped>

</style>

注意:v-slot的缩写是#,但是如果使用#的话,必须始终使用具插槽来代替
<mo #default="slotProps">

3.注意区别对待v-slot="" 和v-slot:name

=和:的区别 一个是slot的name 一个是父组件获取子组件的数据

父组件插入子组件的插槽 👇

//父组件
<child>
  <template v-slot:header> 我是父组件插入子组件了</template>
  👇也可以简写
  <template #header> 我是父组件插入子组件了</template>
</child>
//子组件
<template>
  <div>
  <slot name ="header">我是子组件原来的数据</slot>
  </div>
</template>

是把"我是传出去的数据"插入到了子组件的数据👇

//父组件
<child v-slot="slotProp">
  <template v-slot:header> {{slotProp.name}}</template>
</child>
//子组件
<template>
  <div>
  <slot name ="header" :slotProp="{name: '我是传出去的数据'}">我是子组件原来的数据</slot>
  </div>
</template>
上一篇 下一篇

猜你喜欢

热点阅读