在vue/react项目中单独引入一个js文件,在js文件中使用DOMContentLoaded函数querySelectorAll为空数组解决办法
因为copy的一个网站源码,菜单按钮需要单独添加事件处理函数,但是在一个js脚本中等带DOMContentLoaded完成事件后执行querySelectorAll为空数组:但页面上是有元素的
在Vue3中,由于组件的异步渲染特性,在DOMContentLoaded
事件中尝试获取DOM元素可能会得到空数组,因为此时Vue组件可能还没有完成渲染,所以需要单独处理。
1.使用MutationObserver监听DOM变化
在js脚本文件中使用MutationObserver监听页面变化,然后等可以获取到要查找的元素后,就停止监听,这个时候再执行相应的事件处理函数:
2.轮询检查元素是否存在
原理和第一种方式差不多,推荐使用第一种方式
// 在单独的JS文件中
function pollForElement(selector, callback, interval = 100, timeout = 5000) {const startTime = Date.now();const check = () = >{const elements = document.querySelectorAll(selector);if (elements.length > 0) {callback(elements);return;}if (Date.now() - startTime >= timeout) {console.log('超时: 未找到元素');return;}setTimeout(check, interval);};check();
}pollForElement('.NavigationMenu_menu__05DPv', (elements) = >{console.log('找到元素:', elements);
});
3.自定义事件通知
在window上添加一个事件函数,在vue中等页面渲染完成后,触发这个函数
// 在Vue组件中
onMounted(() = >{window.dispatchEvent(new CustomEvent('vue-mounted'));
});// 在单独的JS文件中
window.addEventListener('vue-mounted', () = >{const elements = document.querySelectorAll('.NavigationMenu_menu__05DPv');console.log('找到元素:', elements);
});