vue获取组件元素和inheritAttrs的使用

我的需求

有些时候,我们需要获取组件的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
    },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的使用

<template>
    <div class="demo">
        //动态绑定到需要的元素上
        <input v-bind="$attrs"  name="" id="">
    </div>
</template>

<script>
    export default {
       //表示不添加在组件的根元素上
       inheritAttrs:false
    }
</script>

相关文章

这篇文章我们将通过debug源码的方式来带你搞清楚defineAsync...
欧阳老老实实的更新自己的高质量vue源码文章,还被某2.6k st...
前言 在Vue3.5版本中响应式 Props 解构终于正式转正了,这个...
组合式 (Composition) API 的一大特点是“非常灵活”,但也因...
相信你最近应该看到了不少介绍Vue Vine的文章,这篇文章我们...
前言 在欧阳的上一篇 这应该是全网最详细的Vue3.5版本解读文...