報(bào)錯(cuò):[Vue warn]: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading '$refs')"
?背景:1.在做vue項(xiàng)目時(shí),在功能彈框中,想實(shí)現(xiàn)新增內(nèi)容。
? ? ? ? ? ? ?2. 報(bào)錯(cuò)原因是要觸發(fā)menuCheckall組件后,才可以提交,因?yàn)椴挥|發(fā)menuCheckall的時(shí)候dom未加載,沒有編譯渲染進(jìn)dom里面。
1.使用了
this.form.menuIds = this.$refs.menuCheckall.$refs.tree.getCheckedKeys();
其中menuCheckall是子組件。
this.$refs['form'].validate((valid) => {
if (valid) {
this.form.menuIds = this.$refs.menuCheckall.$refs.tree.getCheckedKeys();
addOrUpdateRole(this.form).then((res) => {
console.log(res);
if (res.code == 0) {
this.$message.success('提交成功');
this.dialogShow = false;
this.$emit('call-back');
} else {
this.$message.error(res.message);
}
});
}
});
2.但是報(bào)錯(cuò)了,原因是:
mouted加載數(shù)據(jù)以后,隱藏的彈出框并沒有編譯渲染進(jìn)dom里面。所以click彈出的時(shí)候$refs并沒有獲取到dom元素導(dǎo)致? undefined。
對(duì)話是一個(gè)虛擬dom,visible!==true之前,dom未掛載在根節(jié)點(diǎn)上,導(dǎo)致無法識(shí)別。
3.解決辦法:
在網(wǎng)上查了一些解決方法,大致有三種:
1)$nextTick dom下一次更新之后
this.$nextTick(()=>{
this.form.menuIds = this.$refs.menuCheckall.$refs.tree.getCheckedKeys();
})
?這種方法雖然可以提交成功,但是還是會(huì)報(bào)錯(cuò)。
?2)如果是第一次就點(diǎn)擊新增就沒必要reset, 根據(jù)元素undefined判斷
? ? ? ? ? ? ? ? if (this.$refs.menuCheckall.$refs.tree.getCheckedKeys()?!== undefined) {
? ? ? ? ? ? ? ? ? ? this.form.menuIds =this.$refs.menuCheckall.$refs.tree.getCheckedKeys();
? ? ? ? ? ? ? ? }?
此種方法仍報(bào)錯(cuò)也不可提交,不適用于我的情況。
3)在方法前加了關(guān)鍵字async
這個(gè)我沒有試
4)最后發(fā)現(xiàn),問題在v-if
改為v-show即可
原因:
v-show作用:當(dāng)用v-show來隱藏元素時(shí),只會(huì)在初次加載時(shí)渲染此dom節(jié)點(diǎn),之后都是通用display來控制顯隱,如果此時(shí)使用v-if,那會(huì)頻繁的操作dom,會(huì)極大的影響性能,但用display則不會(huì)
而v-if作用:當(dāng)用v-if來隱藏元素時(shí),初次加載時(shí)就不用渲染此dom節(jié)點(diǎn),提升頁面加載速度
文章來源:http://www.zghlxwxcb.cn/news/detail-799764.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-799764.html
到了這里,關(guān)于[Vue warn]: Error in v-on handler: “TypeError: Cannot read properties of undefined (reading ‘$refs‘)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!