TypeError: Cannot read properties of undefined (reading 'setAttribute')

737 阅读1分钟

Vue报错 [Vue warn]: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'setAttribute')"

问题分析

该错误主要是因为调用的时候,该组件还未初始化完成,所以导致获取不了dom元素

 document.getElementsByClassName('el-button--text')[0].setAttribute('style', 'display:none')

问题解决

方法一:我们使用setTimeout把该语句进行延迟加载就ok了

setTimeout(() => {
  document.getElementsByClassName('el-button--text')[0].setAttribute('style', 'display:none') // 隐藏此刻按钮
}, 500)

方法二:为了在数据变化之后等待 Vue 完成更新 DOM ,可以在数据变化之后立即使用 Vue.nextTick(callback) 。这样回调函数在 DOM 更新完成后就会调用。

 this.$nextTick(() => {
  document.getElementsByClassName('el-button--text')[0].setAttribute('style', 'display:none') // 隐藏此刻按钮
})