一、通常情况下都是父组件传递数据给子组件进行展示的(无法改变子组件的展示方式);而作用域插槽允许子组件通过slot向父组件传递数据,类似React中的“以函数为子组件”,由父组件决定渲染的内容(包含绑定事件,样式,HTML标签等);我把数据给你父组件了,你爱怎么处理就怎么处理,极大的提高了灵活性。
二、示例代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" /> <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no,minimum-scale=1.0,maximum-scale=1.0" /> <title>Vue作用域插槽2</title> <script src="https://cdn.bootcss.com/vue/2.5.14/vue.min.js"></script> </head> <body> <div id="root"> <my-list :books="books"> <template slot-scope="scope" slot="book"> <li>{{scope.book.author}}--{{scope.book.name}}</li> </template> </my-list> </div> <script> Vue.component('my-list',{ props: { books: { type: Array, default: () => [] } }, template: ` <ul> <slot v-for="item in books" name="book" :book="item"></slot> </ul> ` }) var app = new Vue({ el: '#root', data: { books: [ { id: 1, author: '李四', name: '《Vue. js 实战》' }, { id: 2, author: '王五', name : '《 JavaScript 语言精粹》' }, { id: 3, author: '张三', name : '《 JavaScript 高级程序设计》' } ] } }) </script> </body> </html>