【发布时间】:2022-01-19 14:16:55
【问题描述】:
我在尝试将属性与 Vue3 一起使用时非常困难。我尝试了几种不同的方法,但它们都未能通过类型检查阶段(例如:yarn build)。
我的项目是使用 Vite 创建的全新 vue3-ts 项目。这是我的组件:
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
name: "Test",
props: {
label: {
type: String as PropType<string>,
required: true,
},
},
methods: {
onClick() {
console.log(this.label); // This line yields an error!
},
},
});
</script>
我收到this.label 不存在的错误:Property 'label' does not exist on type 'CreateComponentPublicInstance<Readonly<ExtractPropTypes<Readonly<ComponentPropsOptions<Data>>>> & ...
(volar 抱怨同样的事情)。
我尝试了几种不同的方法,但都没有更好的运气,它们是:
使用<script setup> 方法定义道具:
<script setup lang="ts">
const props = defineProps({
classes: String,
label: String,
})
</script>
这也会警告未使用的props 变量。这不是什么大问题,但是上面的错误仍然存在。
在我的组件上使用setup 方法:
setup(props) {
defineProps({
classes: String,
label: String,
})
},
使用老式的 props 定义形式,对定义类型有点过分热情:
export default defineComponent({
name: "AppStory",
props: {
label: {
type: String as PropType<string>,
required: true,
},
},
一种稍微不那么热心的方法:
export default defineComponent({
name: "AppStory",
props: {
label: {
type: String,
required: true,
},
},
有没有人有一个使用属性的带有 Vue3 的 SFC 的工作示例?我究竟做错了什么?我在那里找到的所有示例都没有道具,或者不使用 TS。 Vue'3 文档不是非常以 TS 为中心,似乎没有任何示例涵盖这种(相当基本的)场景。
【问题讨论】:
标签: typescript vue.js vue-component