zoukankan      html  css  js  c++  java
  • 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
        },
        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
        }
    </script>
    

  • 相关阅读:
    没提供编码格式,读文件时要怎么推测文件具体的编码
    Spring系列.@EnableRedisHttpSession原理简析
    程序员必备画图技能之——流程图
    痞子衡嵌入式:第一本Git命令教程(7.1)- 清理之缓存(stash)
    痞子衡嵌入式:第一本Git命令教程(6)- 日志(log/reflog/gitk)
    痞子衡嵌入式:第一本Git命令教程(5)- 提交(commit/format-patch/am)
    痞子衡嵌入式:第一本Git命令教程(4)- 转移(add/rm/mv)
    痞子衡嵌入式:第一本Git命令教程(3)- 变动(status/diff)
    痞子衡嵌入式:第一本Git命令教程(2)- 连接(remote/clone)
    痞子衡嵌入式:第一本Git命令教程(1)- 准备(init/config/.gitignore)
  • 原文地址:https://www.cnblogs.com/IwishIcould/p/15583023.html
Copyright © 2011-2022 走看看