默认插槽和具名插槽的概念比较好理解,这里主要以官方文档的案例来讲解一下作用域插槽。
首先是有一个currentUser的组件:
1 <!DOCTYPE html> 2 <html lang="zh-CN"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>Document</title> 8 </head> 9 <body> 10 <div id="app"> 11 <current-user> 12 {{ user.firstName }} 13 </current-user> 14 </div> 15 <script src="vue.min.js"></script> 16 <script> 17 Vue.component('currentUser', { 18 template: ` 19 <span> 20 <slot>{{ user.lastName }}</slot> 21 </span> 22 `, 23 data() { 24 return { 25 user: { 26 firstName: 'w', 27 lastName: 'ts' 28 } 29 } 30 } 31 }) 32 33 new Vue({ 34 el: '#app' 35 }) 36 </script> 37 </body> 38 </html>
然而该页面无法正常工作,因为只有currentUser可以访问到user,出错的地方在这里:
然后,引入一个插槽prop:
1 <span> 2 <slot :user="user"> 3 {{ user.lastName }} 4 </slot> 5 </span>
接着,需要给v-slot带一个值来定义我们提供的插槽 prop 的名字:
1 <current-user> 2 <template v-slot="wts"> 3 {{ wts.user.firstName }} 4 </template> 5 </current-user>
简单的讲作用域插槽就是让插槽内容能够访问子组件中才有的数据,修改后便可以正常工作了。