默認插槽和具名插槽的概念比較好理解,這里主要以官方文檔的案例來講解一下作用域插槽。
首先是有一個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>
簡單的講作用域插槽就是讓插槽內容能夠訪問子組件中才有的數據,修改后便可以正常工作了。