刚在官网看完了keep-alive,就随手翻了翻,看到了插槽的内容
在 2.6.0 中,我们为具名插槽和作用域插槽引入了一个新的统一的语法 (即 v-slot 指令)。它取代了 slot 和 slot-scope 这两个目前已被废弃但未被移除且仍在文档中的 attribute。
What?大变天了?我好像跟不上时代了,既然都看到了,就把官网的内容再过一遍,会的加深记忆,不会的好好学习一下。
正如vue官网所说,slot和slots-cope已经被废弃了,虽然在vue2.x中仍然被支持,但是不会出现到vue3中,就借此机会把官网有关于插槽的内容过一遍。
默认插槽
组件中的内容就默认加载到默认插槽中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <template> <div> <h1>子组件的内容</h1> <slot></slot> </div> </template>
<Child> <h3> 父组件要放入子组件插槽中的内容 </h3> </Child>
|
具名插槽
当子组件中存在多个插槽时,则需要对插槽进行命名用于区分
不对插槽命名则会有默认名为default
1 2 3 4 5 6 7 8 9
| <template> <div> <h1>Title</h1> <slot name="slot1"></slot> <slot name="slot2"></slot> </div> </template>
|
使用新的slot语法
1 2 3 4 5 6 7 8 9 10 11 12
| <Child> <template v-slot:slot1> <img /> <a /> </template> <template #slot2> <img /> <a /> </template> </Child>
|
作用域插槽
slot-scope语法已经被废弃,我们现在使用带值的v-slot来访问作用域插槽
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| <template> <div> <h1>Title</h1> <slot :games="games"></slot> </div> </template> <script> export default { data(){ return { games: [] } } } </script>
<template> <Child> <template v-slot="slotProps"> <ul> <li v-for="item in slotProps.games">{{item}}</li> </ul> </template> </Child> </template>
|
也可以将数据解构使用
1 2 3 4 5 6 7 8 9 10 11 12
| <template> <Child> <template v-slot:default="{games}"> <ul> <li v-for="item in games">{{item}}</li> </ul> </template> </Child> </template>
|
也是可以使用缩写形式的:
1 2 3 4 5 6 7 8 9 10 11 12
| <template> <Child> <template #default="{games}"> <ul> <li v-for="item in games">{{item}}</li> </ul> </template> </Child> </template>
|