vuejs的极大程度的帮助减少了对dom的操作,他主要通过添加ref属性,但是当获取this.$refs属性时,稍有不注意就会输出undefined导致我们对dom节点的操作报错。
this.$refs.xxx为undefined的几种情况记录:
1、在created里钩子函数中调用
原因:created()在实例创建完成后被立即调用。在这一步,实例已完成以下的配置:数据观测 (data observer),属性和方法的运算,watch/event 事件回调。然而,挂载阶段还没开始,$el
属性目前不可见。所以this.$refs压根就调不到那个dom,因为页面还没有挂载上去。
解决:在mounted () 钩子函数中调用
注意:在此种情况中,元素节点一定是直接写在html中的,而不是通过数据或者条件渲染的
2、数据或条件渲染(v-if,v-show)之后的调用
原因:
<template> <div> <p ref="testtext">this is a test data</p> <p v-if="msg" ref="msgtext">{{msg}}</p> <button @click="handleclick">点一下</button> </div> </template> <script> import { settimeout } from 'timers'; export default { data () { return { text: 'message show', msg: '' } }, created () { console.log(this.$refs.testtext) // undefined // this.$refs.testtext.style.color = '#f00' }, mounted () { console.log(this.$refs.testtext) // <p data-v-5752faac="" style="color: rgb(255, 0, 0);">this is a test data</p> console.log(this.$refs.msgtext) // undefined this.$refs.testtext.style.color = '#f00' }, methods: { handleclick () { this.msg = 'msg show' console.log(this.$refs.msgtext) // undefined settimeout(() => { this.$refs.msgtext.style.color = '#eee' console.log(this.$refs.msgtext) // <p data-v-5752faac="" style="color: rgb(238, 238, 238);">msg show</p> }, 0) } } }
如对本文有疑问, 点击进行留言回复!!
offset、client、scroll (width,height、left,top、X,Y)
网友评论