slot的用法

128 阅读1分钟

匿名插槽

父组件

<template>
  <div>
    <child>若子组件没有slot,则这句话不会显示</child>
  </div>
</template>
 
<script>
import Child from './Child.vue'
export default {
  name: 'HelloWorld',
  components:{
    'child':Child
  }
}
</script>

子组件

<template>
  <div>
    <h1>我是子组件</h1>
    <slot></slot>
  </div>
</template> 

浏览器显示

image.png

具名插槽 (多个插槽情况)

父组件

<template>
   <child>
     <h1 slot="h1">标题一</h1>
     <h2 slot="h2">标题二</h2>
     <h3>标题三</h3>  
   </child>
</template>
 
<script>
import Child from './Child.vue'
export default {
  components:{
    'child':Child
  }
}
</script>

子组件

<template>
  <div>
    <h1>我是子组件</h1>
    <slot name="h1"></slot>
    <slot name="hh"></slot>
    <slot></slot>
  </div>
</template>

浏览器显示

image.png

  • 父组件没有slot值的内容则会显示在默认的slot中。
  • 如果子组件中没有默认的slot,父组件没有slot值的内容就会被抛弃。

作用域插槽

自2.6.0起 slot-scope被废弃

作用域插槽是一种子传父传参的方式,解决了普通slot在parent中无法访问child数据的去问题

父组件

<template>
  <Child>
    <template v-slot:attr="props">
      <li>{{props.myname}}</li>
    </template>
  </Child>
</template>
<script>
import Child from './Child.vue'
export default {
  components: {
    Child
  }
}
</script>

子组件

<template>
  <ul>
    <slot name="attr" v-for="item in items" :text="item.text" :myname="item.myname" >
      slot的默认内容
    </slot>
  </ul>
</template>
<script>
export default {
  data () {
    return {
      items: [
        {
          text: 'a',
          myname: 'b'
        },
        {
          text: 'aa',
          myname: 'ab'
        }
      ]
    }
  }
}
</script>
  • 独占默认插槽的缩写语法 被提供的内容只有默认插槽时,组件的标签才可以被当作插槽的模板来使用。这样我们就可以把 v-slot 直接用在组件上:
<current-user v-slot="slotProps"> {{ slotProps.user.firstName }} </current-user>
  • 解构插槽prop 作用域插槽的内部工作原理是将你的插槽内容包裹在一个拥有单个参数的函数里: 可以改写名字,加默认值
function (slotProps) { // 插槽内容 }
v-slot="{ myname:name }"
v-slot="{ myname = 'lll' }"
  • 动态插槽名
v-slot:[dynamicSlotName]

传值

  • 父传子 父组件
<template>
   <child :name="lll" age="18">
     <h3>标题三</h3>  
   </child>
</template>

子组件

<template>
    <div>{{name}}{{age}}</div>
</template>
<script>
export default {
  props: ['name', 'age']
}
</script>
  • 子传父 见作用域插槽