vue官網是這樣介紹的:
包含了父作用域中不作為 prop 被識別 (且獲取) 的特性綁定 (class
和 style
除外)。當一個組件沒有聲明任何 prop 時,這里會包含所有父作用域的綁定 (class
和 style
除外),並且可以通過 v-bind="$attrs"
傳入內部組件——在創建高級別的組件時非常有用。
<div id="app"> A{{msg}} <my-button :msg="msg"></my-button> </div>
首先我們有三個組件A-B-C,然后想A中的屬性傳入C中,基本的做法是這樣的,一層一層通過props往下傳遞
<script> let vm = new Vue({ el: '#app', data: { msg: '100' }, components: { 'MyButton': { props: ['msg'], template: `<div>B<my-input :msg="msg"></my-input></div>`, components: { 'MyInput': { props: ['msg'], template: '<div>C{{msg}}</div>' } } }, } }) </script>
但是B中並沒有使用到A中傳遞過來的屬性,寫props代碼就是多余的了,那么$attrs可以接受上級傳遞過來的屬性,那么我們就可以直接把$attrs傳入下級
<script> let vm = new Vue({ el: '#app', data: { msg: '100' }, components: { 'MyButton': { // props: ['msg'], template: `<div>B<my-input v-bind="$attrs"></my-input></div>`, components: { 'MyInput': { props: ['msg'], template: '<div>C{{msg}}</div>' } } }, } }) </script>
注意組件別寫錯了,組件是在父級模板中使用的,最外層的也是模板,el表示模板掛載在哪個元素的位置