You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue2中使用<script setup>简单示例报错原因排查

Vue 2.7 使用<script setup>时出现"Property or method is not defined"报错的原因

问题描述

我之前用类式写法开发Vue2组件,现在打算迁移到Composition API。根据文档,Vue 2.7支持Composition API和<script setup>单文件组件写法,但写了一个简单示例却报错。

package.json 配置:

"vue": "2.7.14"

test.vue 代码:

<script setup>
  import {ref} from 'vue'

  const count = ref(0);
</script>

<template>
  <button @click="count++">{{ count }}</button>
</template>

代码编译正常,但浏览器控制台抛出错误:

App.js:144 Property or method "count" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties. 

found in

---> <Test> at test.vue

请问这个示例报错的原因是什么?


回答

这个报错的核心原因是你的构建工具版本未适配Vue 2.7的<script setup>语法。

Vue 2.7虽然原生支持Composition API和<script setup>,但需要对应的构建工具提供语法支持:

  • 若使用vue-cli,需要将@vue/cli-service升级到~5.0.0版本,旧版cli-service无法正确解析Vue 2.7的<script setup>。
  • 若直接用webpack + vue-loader,需要将vue-loader升级到^15.10.0及以上版本,同时确保vue-template-compiler也同步升级到2.7.x版本。

旧版本的构建工具不会处理<script setup>里的变量自动暴露逻辑,导致编译后的组件实例上没有挂载count变量,模板渲染时就会提示未定义。

只要升级对应的构建工具依赖,你的示例代码本身没有问题,就能正常运行。

内容的提问来源于stack exchange,提问作者Reynicke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 19:32:43