隐藏

Vue3 项目中使用setup()函数报错,script setup cannot contain ES module exports

发布:2023/10/7 9:36:26作者:管理员 来源:本站 浏览次数:598

问题


Vue3 项目中使用 setup() 函数,代码如下

复制代码


<script setup>

 import { useStore } from "../stores/store.js";

 export default {

   setup() {

     const store = useStore();

     return {

       store,

     };

   },

 };

</script>


复制代码


vite 启动时控制台报了以下错误。


[vite] Internal server error: [@vue/compiler-sfc] <script setup> cannot contain ES module exports. If you are using a previous version of <script setup>, please consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.


翻译成中文的意思是,内部服务错误,:[@vue/compiler-sfc] <script setup> 不能包含 ES 模块导出。如果您正在使用 <script setup>,请更新版本。


原因


其实问题就出在,官方文档提供了两种写法,我们把这两种写法混用了,


一种是:<script> 标签里面配置 setup


另一种是:export default 类里配置 setup() 方法


我们只需要使用一种方法即可,混用了就会报错了。

解决


我们来重写上面的例子,下面两种方法都可以,It's up to u。

第一种


<script setup>

import {useStore} from "../stores/store.js";

const store = useStore();

</script>


第二种

复制代码


<script>

import { defineComponent } from 'vue'

import {useStore} from "../stores/store.js";

export default defineComponent({

 setup() {

   const store = useStore();

   return {

     store,

   }

 }

})

</script>


复制代码