Vue.js 3中点击按钮无法调整DIV大小的问题及修正方法
Vue3 修改DIV宽度报错 "Cannot read properties of undefined (reading 'style')" 的修复方案
错误原因分析
- 语法错误:
changeWidth函数定义缺少大括号与分号,导致函数结构不完整,引发this指向异常或函数未正确绑定。 - Vue3 API 使用差异:若使用组合式API(
<script setup>),无法通过this.$refs访问DOM引用,需用ref()声明引用变量。 - DOM 访问时机:需确保DOM挂载完成后再操作
$refs,避免组件未挂载时访问导致引用为undefined。
修复方案
情况1:使用选项式API
修正JavaScript语法错误,同时增加引用存在性判断,提升代码健壮性:
<div ref="block2" id="block2"> <button v-on:click="changeWidth">调整宽度</button> </div>
export default { methods: { changeWidth() { if (this.$refs.block2) { this.$refs.block2.style.width = "150px"; } } }, mounted() { // 组件挂载后确认ref已生效 console.log(this.$refs.block2); } }
情况2:使用组合式API(Vue3推荐写法)
通过ref()声明DOM引用变量,直接访问操作:
<div ref="block2" id="block2"> <button @click="changeWidth">调整宽度</button> </div>
<script setup> import { ref, onMounted } from 'vue'; const block2 = ref(null); const changeWidth = () => { if (block2.value) { block2.value.style.width = "150px"; } }; onMounted(() => { console.log(block2.value); // 确认DOM已挂载 }); </script>
CSS 样式保持不变
#block2 { position:absolute; z-index:5000; width:50px; height:50px; background-color: #7d7d7d; transition: all .3s ease-in; }
内容的提问来源于stack exchange,提问作者user22190533
相关产品推荐
相关产品推荐

