返回

如何解决 Vue 中 `@vue/compiler-sfc` 编译 `<script setup>` 代码时 `$setup` 缺失的错误?

vue.js

解决 @vue/compiler-sfc 编译 <script setup> 代码时 $setup 缺失的错误

问题概述

在使用 @vue/compiler-sfc 编译包含 <script setup> 语法的 .vue 文件时,可能会遇到 $setup 参数缺失的错误,从而导致运行时错误。

错误原因

此错误通常是由过低的 @vue/compiler-sfc 编译器版本引起的,它无法正确处理 <script setup> 语法。

解决方案

方法 1:升级 @vue/compiler-sfc

  • 升级 @vue/compiler-sfc3.0.0 或更高版本。

方法 2:在 compiler.js 中进行更改

  • compiler.js 中,将以下代码添加到 transformVueSFC 函数中:
import { transformVueSFC } from '@vue/compiler-sfc';

const templateOptions = {
  // ...
  compilerOptions: {
    // ...
    scopeId: hasScoped ? `data-v-${id}` : undefined,
    // 加入以下行
    isCustomElement: true,
  },
};

方法 3:使用 <template setup>

  • 使用 <template setup> 作为 <script setup> 的替代语法。<template setup>@vue/compiler-sfc 3.0.0+ 版本兼容。

深入探讨