Vue 3.2〈script setup>标记和TypeScript类型的问题

fd3cxomn  于 2023-01-05  发布在  Vue.js
关注(0)|答案(3)|浏览(305)

我正在尝试将Vue 3.2 <script setup>标记与TypeScript一起使用。
我有一个简单的用例,希望在模板中显示用户ID。
我的代码在技术上是工作的。它显示用户ID很好。
但有两件事很奇怪...
1.我定义了一个user prop,类型为User,是从Firebase SDK导入的。这可以正常工作,但User类型出现错误,内容如下:'User' only refers to a type, but is being used as a value here. ts(2693).为什么会出现此错误,如何修复?
1.帮助文档说我不需要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>
2ekbmq32

2ekbmq321#

script setup中,您可以像这样定义props:

<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'
  }
bf1o4zei

bf1o4zei2#

这为我解决了问题
第一个月

extends: [...],
env: {
  "vue/setup-compiler-macros": true,
},
rules: {...}
xkrw2x1b

xkrw2x1b3#

我不建议在.eslintrc中设置全局只读变量,这是不正确的,**只隐藏了您可能看到的配置问题的一部分。
因此,开始,您需要在VSCode中安装Volar并卸载vetur,然后需要使用以下命令将vue eslint解析器添加到项目中:

npm install --save-dev eslint vue-eslint-parser

并且在你的.eslintrc.js文件中,它应该在你的项目的根(vue-project/.eslintrc)中,你将想要设置你的分析器到vue-eslint-parser .一个简单的.eslintrc文件对于一个vue ^3.2.6项目可以看起来像这样:

module.exports = {
    root: true,
    env: {
        node: true,
    },
    extends: [
        'plugin:vue/vue3-essential',
        'plugin:vue/vue3-recommended',
    ],
    parser: "vue-eslint-parser",
}

这不是一个最小的例子,甚至不是完整的vue,而是一个很好的开始来修复这个特定的选项,并在你的项目中获得linting。注意,添加更多的到extends数组可能会改变linting并再次打破它,即'eslint:recommended'。至于它的价值,我不太确定Vue的开箱即用的linting情况,他们提供的实际上是完美的,它仍然需要一些工作。
我推荐一些额外的阅读,请访问以下链接:
https://vuejs.org/guide/scaling-up/tooling.html#linting
https://github.com/vuejs/vue-eslint-parser
https://github.com/vuejs/core/issues/4994#issuecomment-1125677494

相关问题