Vue.js入门(9)组件插槽slot
序言
组件的最大特性就是复用性,而用好插槽能大大提高组件的可复用能力
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript" src="../../assets/js/vue.js"></script> </head> <body> <div id="app"> <!-- 父组件向子组件传递内容 --> <alert-box>有bug发生</alert-box> <alert-box>有一个警告</alert-box> <alert-box></alert-box> </div> <template id="slottmpl"> <div> <strong>ERROR:</strong> <!-- 子组件插槽 --> <slot>默认内容</slot> </div> </template> <script type="text/javascript"> // 子组件插槽 Vue.component('alert-box', { template:'#slottmpl', }); var vm = new Vue({ el: '#app', data: { } }); </script> </body> </html>
具名插槽
-
具有名字的插槽
- 使用 <slot> 中的 "name" 属性绑定元素
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript" src="../../assets/js/vue.js"></script> </head> <body> <div id="app"> <base-layout> <p slot='header'>标题信息</p> <p>主要内容1</p> <p>主要内容2</p> <p slot='footer'>底部信息信息</p> </base-layout> <base-layout> <template slot='header'> <p>标题信息1</p> <p>标题信息2</p> </template> <p>主要内容1</p> <p>主要内容2</p> <template slot='footer'> <p>底部信息信息1</p> <p>底部信息信息2</p> </template> </base-layout> </div> <template id="slottmpl"> <div> <header> <slot name='header'></slot> </header> <main> <slot></slot> </main> <footer> <slot name='footer'></slot> </footer> </div> </template> <script type="text/javascript"> /* 具名插槽 */ Vue.component('base-layout', { template:'#slottmpl', }); var vm = new Vue({ el: '#app', data: { } }); </script> </body> </html>
作用域插槽
-
父组件对子组件加工处理
-
既可以复用子组件的slot,又可以使slot内容不一致
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript" src="../../assets/js/vue.js"></script> </head> <style type="text/css"> .current { color: orange; } </style> <body> <div id="app"> <fruit-list :list='list'> <template slot-scope='slotProps'> <strong v-if='slotProps.info.id==3' class="current">{{slotProps.info.name}}</strong> <span v-else>{{slotProps.info.name}}</span> </template> </fruit-list> </div> <template id="slottmpl"> <div> <li :key='item.id' v-for='item in list'> <slot :info='item'>{{item.name}}</slot> </li> </div> </template> <script type="text/javascript"> /* 作用域插槽 */ Vue.component('fruit-list', { props: ['list'], template:'#slottmpl', }); var vm = new Vue({ el: '#app', data: { list: [{ id: 1, name: 'apple' },{ id: 2, name: 'orange' },{ id: 3, name: 'banana' }] } }); </script> </body> </html>