一、概念
vue官網定義如下:
包含了父作用域中不作為 prop 被識別 (且獲取) 的 attribute 綁定 (class
和 style
除外)。當一個組件沒有聲明任何 prop 時,這里會包含所有父作用域的綁定 (class
和 style
除外),並且可以通過v-bind="$attrs"
傳入內部組件——在創建高級別的組件時非常有用。
二、用處
vue中一個比較令人煩惱的事情是屬性只能從父組件傳遞給子組件。這也就意味着當你想向嵌套層級比較深組件數據傳遞,只能由父組件傳遞給子組件,子組件再傳遞給孫子組件。
常用的幾個組件之間數據傳遞的方法有如下幾個:
1、通過 props
的方式向子組件傳遞(父子組件)
2、vuex
進行狀態管理
3、非父子組件的通信傳遞 Vue Event Bus
,使用Vue的實例,實現事件的監聽和發布,實現組件之間的傳遞
4、$attrs的方式
三、示例
在vue中新建三個組件,分別為父組件(Father),子組件(Son)和孫子組件(Grandson)。
父組件(Father)的代碼如下:
<template> <div style="background: aquamarine"> <div>Here is Father</div> <son :sonAge=20 :grandsonAge=10></son> </div> </template> <script> import Son from "./Son"; export default { name: "Father", components: { Son }, } </script> <style scoped> </style>
子組件(Son)的代碼如下:
<template> <div style="background: antiquewhite"> <div>Here is Son</div> <div>Son age:{{$attrs.sonAge}}</div> <grandson v-bind="$attrs"></grandson> </div> </template> <script> import Grandson from "./Grandson"; export default { name: "Son", components: { Grandson }, } </script> <style scoped> </style>
孫子組件(Grandson)的代碼如下:
<template> <div style="background: gainsboro"> <div>Here is Grandson</div> <div>Grandson age: {{$attrs.grandsonAge}}</div> </div> </template> <script> export default { name: "Grandson", } </script> <style scoped> </style>
效果如下所示:
孫子組件(Grandson)上通過v-bind的方式就可以把子組件(Son)中未聲明,而孫子組件(Grandson)需要從父組件(Father)中獲取的數據傳輸過來。