v-slot
vue 在 2.6.0 中,具名插槽和作用域插槽引入了一个新的统一的语法 :v-slot 指令。
它取代了 slot 和 slot-scope 这两个目前已被废弃但未被移除且仍有用的特性。
但是将会在vue 3 中,这两个指令将会被废弃
vue 2.6.0
之后 v-slot
只能用在 template上,用在 div 或 p 这种标签上是会报错的
子组建
<template>
<div class="my-card">
<!-- 把数据传给父组件,接收作用域插槽 !:user=user :text=text 传给外面用-->
<slot name="scope_slot" :user=user :text=text></slot>
<!-- 接收具名插槽 !-->
<slot name="named_slot"></slot>
<!-- 接收默认匿名插槽 !-->
<slot></slot>
</div>
</template>
<script>
export default {
name:'card',
data(){
return{
user:[
{
name:'jenson',
age:'21'
},
{
name:'wjh',
age:'20'
}
],
text:{
msg:'作用域插槽'
}
}
}
}
</script>
<template>
<div class="home-container">
<h1>Home</h1>
<card>
<!-- 作用域插槽 v-slot:插槽名 = '接受子组件数据的对象名,可自定义' v-slot : 插槽名称 = ' 传过来的值 '-->
<template v-slot:scope_slot = 'item'>
<h1>{{item.text.msg}}</h1>
<div v-for="u in item.user" :key='u'>
<h3>{{u.name}}</h3>
</div>
</template>
<!-- 具名插槽 v-slot:插槽名字 -->
<template v-slot:named_slot>
<h1>具名插槽</h1>
</template>
<template>
<h1>匿名插槽</h1>
</template>
</card>
</div>
</template>
缩写方式
<template>
<div class="home-container">
<h1>Home</h1>
<card>
<!-- 2.6.0 之后 具名插槽 v-slot:scope_slot 可以缩写为 #scope_slot ,
必须是有参数才能这样写!!! # = "xxx " 这样是不行的
#default = 'xxx' 这样才可以-->
<template #scope_slot = 'item'>
<h1>{{item.text.msg}}</h1>
<div v-for="u in item.user" :key='u'>
<h3>{{u.name}}</h3>
</div>
</template>
<!-- 具名插槽 v-slot:插槽名字 -->
<template #named_slot>
<h1>具名插槽</h1>
</template>
<template>
<h1>匿名插槽</h1>
</template>
</card>
</div>
</template>