vue - 插槽slot
Posted cisum
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue - 插槽slot相关的知识,希望对你有一定的参考价值。
描述:插槽,也就是slot,是组件的一块html模板,一个slot最核心的两个问题是显示不显示和怎样显示
插槽分类:
1.1 单个插槽(单个插槽,别名默认插槽、匿名插槽,不用设置name属性)
1.2 具名slot(插槽加了name属性,就变成了具名插槽。具名插槽可以在一个组件中出现N次,出现在不同的位置)
1.3 作用域slot(vue2.5版本中slot-scope取代了scope,来实现作用域插槽,主要用在组件调用中,具体在template标签上面使用slot-scope来获取插槽slot上面的属性值,获取值的为一个对象,slot-scope=”它可以取任意字符串”,在element-ui的组件中经常看到)
<!-- 单个插槽--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <children1> <span>12345</span> </children1> </div> <script type="text/javascript"> var app = new Vue({ el: ‘#app‘, components: { children1: { template: "<button><slot></slot>单个插槽</button>" } } }); </script> </body> </html>
1 <!-- 具名插槽 --> 2 <!DOCTYPE html> 3 <html lang="en"> 4 5 <head> 6 <meta charset="UTF-8"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 9 <title>Document</title> 10 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> 11 </head> 12 13 <body> 14 <div id="app"> 15 <children2> 16 <span slot="first" @click="tobeknow">12345</span> 17 <span slot="second">56789</span> 18 </children2> 19 </div> 20 21 <script type="text/javascript"> 22 var app = new Vue({ 23 el: ‘#app‘, 24 methods: { 25 tobeknow: function () { 26 console.log("It is the parent‘s method"); 27 } 28 }, 29 components: { 30 children2: {//这个无返回值,不会继续派发 31 template: "<button><slot name=‘first‘></slot>具名插槽,<slot name=‘second‘></slot></button>" 32 } 33 } 34 }); 35 </script> 36 </body> 37 38 </html>
1 <!-- 作用域插槽 --> 2 <!DOCTYPE html> 3 <html lang="en"> 4 5 <head> 6 <meta charset="UTF-8"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 9 <title>Document</title> 10 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> 11 </head> 12 13 <body> 14 <div id="app"> 15 <!-- 将数据传递给组件 --> 16 <tb-list :data="data"> 17 <!-- 获取slot上面的值 --> 18 <template slot-scope="scope"> 19 <p>索引:{{JSON.stringify(scope)}}</p> 20 <p>索引:{{scope.$index}}</p> 21 <p>姓名:{{scope.row.name}}</p> 22 <p>年龄: {{scope.row.age}}</p> 23 <p>性别: {{scope.row.sex}}</p> 24 </template> 25 </tb-list> 26 </div> 27 28 <script type="text/javascript"> 29 var app = new Vue({ 30 el: ‘#app‘, 31 data: { 32 data: [{ 33 name: ‘kongzhi1‘, 34 age: ‘29‘, 35 sex: ‘man‘ 36 }] 37 }, 38 components: { 39 // 作用域slot 40 ‘tb-list‘: { 41 template: 42 `<ul> 43 <li v-for="(item, index) in data"> 44 <slot :row="item" :$index="index"></slot> 45 </li> 46 </ul>`, 47 // 获取值 48 props: [‘data‘] 49 } 50 } 51 }); 52 </script> 53 </body> 54 55 </html>
以上是关于vue - 插槽slot的主要内容,如果未能解决你的问题,请参考以下文章