我的需求
有些時候,我們需要獲取組件的DOM元素
有些小伙伴會說,這還不簡單
直接使用this.$ref.xx不就可以了嗎
我們來看一下,是不是我們想的那樣簡單
組件內容
<template>
<div class="demo">
<h2>我是組件</h2>
<div>我是組件中的數據</div>
</div>
</template>
使用組件的頁面
<template>
<div>
我是頁面測試一
<testcom ref="testRef"></testcom>
</div>
</template>
<script>
import testcom from "../components/test-com.vue"
export default {
components:{
testcom:testcom
},
mounted(){
console.log('獲取組件內的DOM',this.$refs.testRef);
}
}
</script>

現在的實際結果
我想在這個頁面內,獲取組件內的DOM元素
也就是獲取
<div>
我是頁面測試一
<testcom ref="testRef"></testcom>
</div>
實際上壓根獲取的就是這樣的
我們並沒有獲取到組件內的DOM元素。
而是獲取的是Vue的組件
那要怎么樣才可以獲取組件內的元素呢
解決辦法使用$el
<template>
<div>
我是頁面測試一
<testcom ref="testRef"></testcom>
</div>
</template>
<script>
import testcom from "../components/test-com.vue"
export default {
components:{
testcom:testcom
},
mounted(){
console.log('獲取組件內的DOM',this.$refs.testRef.$el);
}
}
</script>

需求描述
有些時候我們需要封裝組件
封裝組件的時候,
我們需要屬性直接設置在某一個指定的元素上。
<template>
<div>
我是測試頁面
<testcom type="text"></testcom>
<testcom type="password"></testcom>
</div>
</template>
組件
<template>
<div class="demo">
<input name="" id="">
</div>
</template>

實際結果
屬性結果直接被添加到跟元素上去了。
因為這個是vue規定的
我們如何讓屬性設置在指定的元素上面呢?
我們可以使用inheritAttrs
官網對:inheritAttrs的解釋
如果你不希望組件的根元素有繼承特性,你可以在組件的選項中設置 inheritAttrs: false。
解決辦法inheritAttrs的使用
<template>
<div class="demo">
//動態綁定到需要的元素上
<input v-bind="$attrs" name="" id="">
</div>
</template>
<script>
export default {
//表示不添加在組件的根元素上
inheritAttrs:false
//inheritAttrs 讀音 [ ɪnˈherɪt] [in her t ATTRS】
}
</script>
