Vue3实例setup函数内无法访问HTML DOM的原因咨询
问题原因及解决方法
核心原因:
setup函数的执行时机是组件实例初始化阶段,这时候Vue还没把组件的DOM渲染到页面上,所以调用document.getElementById('here')自然找不到对应的元素。而createApp外部的代码,一般是在页面DOM已经加载完成后执行的(比如写在</body>标签前),所以能正常获取到DOM节点。正确的处理方式:
- 使用Vue的生命周期钩子
onMounted:在组件挂载完成后(DOM已渲染)执行DOM操作,代码示例:import { onMounted } from 'vue' setup() { onMounted(() => { const el = document.getElementById('here') // 这里就能正常获取到元素了 }) } - 更推荐的Vue式写法:用
ref绑定DOM元素,避免直接操作DOM,代码示例:<template> <div ref="hereEl">目标元素</div> </template> <script setup> import { ref, onMounted } from 'vue' const hereEl = ref(null) onMounted(() => { // hereEl.value就是对应的DOM元素 console.log(hereEl.value) }) </script>
- 使用Vue的生命周期钩子
查找相关文档的关键词:Vue3 setup 执行时机、Vue3 生命周期钩子、Vue3 ref DOM 引用
内容的提问来源于stack exchange,提问作者hoo
相关产品推荐
相关产品推荐

