nuxt3 自定义类型的简单指南

Dom*_* Zi 3 typescript vue.js nuxtjs3

我有一个 vue 文件,我想在其中使用自定义类型:

/* 
file: /components/Grid.vue 
*/

<script setup>
// define Section type
interface Section {
  type: string;
  img: string;
  heading: string;
  content: string;
}

const props = defineProps < {
  sections: Section[],
  baseUrl: string
} > ();
const sections = ref(props.sections);
const baseUrl = ref(props.baseUrl);
</script>
Run Code Online (Sandbox Code Playgroud)

它抛出ERROR [@vue/compiler-sfc] Unexpected reserved word 'interface'. (3:0)

我究竟做错了什么?

Kyr*_*ony 5

你只是忘记了一件事。您必须包含打字稿的属性!

<script setup lang="ts">
Run Code Online (Sandbox Code Playgroud)

lang="ts"属性让 Vue 知道您正在使用 TypeScript。以下是文档的链接: https://vuejs.org/guide/typescript/overview.html#usage-in-single-file-components

  • 谢谢!我现在遇到了这个问题,我想外包这些类型。我将接口定义写入 .nuxt/nuxt.d.ts,如 https://nuxt.com/docs/guide/concepts/typescript 中所述,但它们的读取不正确。我把类型定义放在哪里? (2认同)