解决this.refs.xx返回undefind的问题

在vue中需要获取Dom时可以给元素添加ref属性,然后通过this.$refs.xx去获取Dom元素, 但是在获取时可能会返回undefined导致我们对Dom节点的操作报错。因为在Vue生命周期中的created()钩子函数是对模板和数据进行初始化,$el还没有挂载到Dom节点上,所以当使用this.$refs.xx去获取元素就会返回undefind,而在mounted()钩子函数的$el已经挂载到Dom节点上了所以可以使用this.$refs.xx来获取Dom节点。
  1. 元素标签绑定ref属性时,使用mounted()钩子函数获取
<template>
    <div>
        <p ref='content'></p>
    </div>
</template>
created(){
    console.log(this.$refs.content) // undefind
},
mounted(){
    console.log(this.$refs.content)
},
  1. 当元素标签同时绑定ref属性和v-if或v-show时,使用定时器setTimeOut()方法来获取
<template>
    <div>
        <p ref='contentShow' v-if="show"></p>
        <button @click='handlerContentShow()'></button>
    </div>
</template>
mounted(){
    console.log(this.$refs.contentShow) // undefind
},
methods(){
    handlerContentShow(){
        console.log(this.$refs.contentShow) // undefind
        setTimeout(function(){
            console.log(this.$refs.contentShow)
        },100)
    }
},
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值