inheritAttrs和$attrs的做用:vue
當須要將父組件的props傳遞到子組件中,而子組件的須要接收到props的節點有父級容器,那麼就須要用到這兩個屬性。app
將inheritAttrs設置爲false,在子組件須要接收props的節點上加上 v-bind='$attrs'ide
封裝一個input組件:spa
一、components/MyInput.vue:component
<template> <input /> </template>
二、使用:blog
<template> <div id="app"> <MyInput v-model="message" type='text' placeholder="請輸入用戶名"></MyInput> <MyInput v-model="message" type='password' placeholder="請輸入密碼"></MyInput> </div> </template> <script> import MyInput from '@/components/MyInput' export default { data() { return { message: 123 } }, components: { MyInput } } </script>
三、效果:ip
但每每有的時候封裝的input外層有層盒子,以下:input
<template> <div class="input-container"> <input /> {{$attrs}} </div> </template>
此時,能夠看到父組件傳來的屬性都綁定到父容器身上了,因此沒有效果it
將inheritAttrs設置爲falseclass
<script> export default { inheritAttrs: false } </script>
會發現父容器和input都沒有了父組件傳來的屬性
再在須要接收父組件屬性的標籤上經過 v-bind='$attrs' 接收父組件的屬性
<template> <div class="input-container"> <input v-bind="$attrs" /> {{$attrs}} </div> </template> <script> export default { inheritAttrs: false } </script>
就能夠正常顯示了
要注意,當使用props接收了屬性,那麼這個屬性就不在$attrs中了
<template> <div class="input-container"> <input v-bind="$attrs" /> {{$attrs}} </div> </template> <script> export default { props: ['value'], inheritAttrs: false } </script>
能夠經過 :value='value' 綁定
<template> <div class="input-container"> <input v-bind="$attrs" :value="value" /> {{$attrs}} </div> </template> <script> export default { props: ['value'], inheritAttrs: false } </script>