一、组件插槽的作用 父组件向子组件传递内容
二、组件插槽基本用法 1.插槽位置
Vue.component('alert-box',{ template:` <div class="demo-alert-box"> <strong>Error!</strong> <slot></slot> </div> ` }) 2.插槽内容 //如果<alert-box></alert-box>里面没有传递内容,默认<slot></slot>内容 //如果传递了内容那个<alert-box></alert-box>覆盖<slot></slot>内容 <alert-box>Something bad happened.</alert-box>三、具名插槽用法 1.插槽定义
<div class="container"> <header> <slot name="header"></slot> </header> <main> <slot ></slot> </main> <footer> <slot ></slot> </footer> </div> 2.插槽内容 <base-layout> <h1 slot="header">标题内容</h1> //template只是相当于临时包裹header信息,显示出的还是header /* <template slot="header"> <p>标题信息</p> <p>标题信息1</p> </template > */ <p>主要内容1</p> <p>主要内容2</p> <p slot="footer">底部内容</p> </base-layout>四、作用域插槽 应用场景:父组件对子组件的内容进行加工处理 1.插槽定义
<ul> <li v-for="item in list" v-bind:key="item.id"> <slot v-bind:item="item"> {{item.name}} </slot> </li> </ul>2.插槽内容
<fruit-list v-bind="list"> //slot-scope获取子组件的数据 <template slot-scope="slotProps"> <strong v-if="slotProps.item.current"> {{slotProps.item.text}} </strong> </template> </fruit-list>例:作用域插槽的基本用法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </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> <script type="text/javascript" src="js/vue.js"></script> <script type="text/javascript"> /* 作用域插槽 */ Vue.component('fruit-list', { props: ['list'], template: ` <div> <li :key='item.id' v-for='item in list'> <slot :info='item'>{{item.name}}</slot> </li> </div> ` }); var vm = new Vue({ el: '#app', data: { list: [{ id: 1, name: 'apple' },{ id: 2, name: 'orange' },{ id: 3, name: 'banana' }] } }); </script> </body> </html>