1. 程式人生 > 其它 >Vue3 專案中使用setup()函式報錯,script setup cannot contain ES module exports

Vue3 專案中使用setup()函式報錯,script setup cannot contain ES module exports

問題

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>