我正在嘗試在<script setup>TypeScript 中使用 Vue 3.2標簽。
我有一個簡單的用例,我想在模板中顯示用戶 ID。
我的代碼在技術上有效。它顯示用戶 ID 就好了。
但是有兩個奇怪的事情......
我定義了一個
userprop,它的型別User是我從 Firebase SDK 匯入的。這有效,但我在User型別上收到錯誤訊息:'User' only refers to a type, but is being used as a value here. ts(2693)。為什么我會收到此錯誤以及如何修復它?在幫助檔案說,我不需要
import { defineProps } from "vue";。但是,如果我不進行匯入,則會出現'defineProps' is not defined錯誤。這令人困惑。當檔案另有說明時,為什么我被迫匯入它?
這是我的完整代碼:
<template>
<div>Logged in as {{ user.uid }}</div>
</template>
<script setup lang="ts">
import { defineProps } from "vue"; //Docs say this is not needed, but it throws an error without it
import { User } from "firebase/auth";
defineProps({
user: {
type: User, //ERROR: 'User' only refers to a type, but is being used as a value here. ts(2693)
required: true,
},
});
</script>
uj5u.com熱心網友回復:
在script setup你可以這樣定義,而不是道具:
<template>
<div>Logged in as {{ user.uid }}</div>
</template>
<script setup lang="ts">
import { defineProps } from "vue"; //Docs say this is not needed, but it throws an error without it
import { User } from "firebase/auth";
defineProps<{ user: User }>();
</script>
另一種解決方案是@bassxzero 建議的,您可以使用
defineProps<{ user: { type: Object as PropType<User>; required: true } }>()
不使用withDefaults它將自動需要
另外,關于:
import { defineProps } from "vue"; //Docs say this is not needed, but it throws an error without it
你實際上不需要匯入它,但你需要在里面定義它 .eslitrc.js
globals: {
defineProps: 'readonly',
defineEmits: 'readonly',
defineExpose: 'readonly',
withDefaults: 'readonly'
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358856.html
標籤:打字稿 火力基地 Vue.js Vuejs3 vue-composition-api
