Appearance
整理 Vue 开发中最常遇到的报错,帮你快速定位问题。
找不到模块 ./App.vue 的声明文件
无法找到模块"./App.vue"的声明文件。"path/App.vue"隐式拥有 "any" 类型。
这是 TypeScript 不认识 .vue 文件导致的。在 src/ 下创建文件 env.d.ts:
typescript
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
如果项目是用 npm create vue@latest 创建的,这个文件已经自带了,不用手动加。
ref 忘了用 .value
typescript
const count = ref(0)
// ❌ console.log(count) // 打印 RefImpl { ... } 对象,不是数字
// ✅ console.log(count.value) // 打印 0
// ❌ count++ // 语法上能过但不会触发响应式
// ✅ count.value++
💡 Tip:记住 在 <script> 里操作 ref 必须用 .value,模板里不需要。
reactive 整体替换丢失响应式
typescript
// ❌ 这样会丢响应式
let state = reactive({ count: 0 })
state = { count: 1 } // state 指向了新对象,Proxy 包装没了
// ✅ 修改属性
state.count = 1
// 或者用 ref 代替,支持整体替换
const state = ref({ count: 0 })
state.value = { count: 1 } // ✅ ref 支持替换
defineProps 类型声明错误
typescript
// ✅ 纯类型声明
const props = defineProps<{ title: string }>()
// ✅ 运行时声明(不用 TS 时可以这样)
const props = defineProps({ title: { type: String, required: true } })
// ❌ 不能混合使用
const props = defineProps({ title: String })<{ title: string }>
两种声明方式只能选一种。
v-for 缺少 :key
[vue/require-v-for-key] Elements in iteration expect to have 'v-bind:key' directives.
写 v-for 但没加 :key。加上就好了:
vue
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
组件命名冲突
[Vue warn]: Do not use built-in or reserved HTML elements as component id: header
组件名和 HTML 原生标签重名了。解决:用多单词命名,如 AppHeader 而不是 Header。
$refs 访问时机错误
TypeError: Cannot read properties of undefined (reading 'focus')
在 mounted 之前访问了 $refs。确保在 mounted() 生命周期或之后(如事件回调中)访问。
v-html 没有任何内容显示
vue
<div v-html="htmlContent"></div>
检查 htmlContent 的值——如果它是 null 或空字符串,自然什么都不显示。另外注意:v-html 会覆盖元素内的所有内容。
双向绑定不生效
vue
<input v-model="formData.name" /> <!-- ❌ formData 不是响应式的 -->
formData 必须是用 reactive 创建的,或 formData.name 是 ref。如果 formData 是个普通对象,v-model 不会生效。
快速排错清单
| 症状 | 首先检查 | | 页面没更新 | 数据是不是响应式的(ref/reactive/data) | | 子组件收不到数据 | props 声明了吗?传值加冒号了吗? | | 事件不触发 | 方法名拼写对不对?@click 写了吗? | | 样式不生效 | scoped 了吗?class 名对不对? | | 组件报错不显示 | 检查浏览器控制台(F12)的错误信息 |