Skip to content

[vite] Internal server error: [@vue/compiler-sfc] defineProps()in <script setup> cannot reference locally declared variables because it will be hoisted outside of the setup() function.

Image text

Image text

原因:

当我们使用script setup的时候,其实是编译器帮我们把代码编译回去setup的方法,类似我们在defineComponent里写setup方法,所以setup本身是一个独立的作用域(setup scope)。

而vue组件本身是一个js文件,也就是script方法里也是一个作用域(module scope)。

也就是说一个vue组件其实同时具备了两个作用域。

因此,在defineProps里定义default函数的时候不应该引用setup作用域的变量。

因为props本身应该是属于module scope,跟setup是同级的

解决办法:

第一种:将数据在外面的文件里定义好,直接引入,然后在props里使用

Image text

Image text

第二种:在组件里新加一个<script></script>标签,在这里面引入方法,生成数据,然后将数据加入props中

如有转载或 CV 的请标注本站原文地址