I've hit a roadblock while attempting to utilize properties in Vue3. Despite trying various methods, I keep facing issues during the type-check phase (e.g.: yarn build
).
The project I'm working on is a fresh Vue3-ts project created using Vite. Below is an example of my component:
<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 triggers an error!
},
},
});
</script>
I receive an error stating that this.label
does not exist:
Property 'label' does not exist on type 'CreateComponentPublicInstance<Readonly<ExtractPropTypes<Readonly<ComponentPropsOptions<Data>>>> & ...
(volar
raises a similar issue).
I've experimented with different approaches but haven't had any success, including:
Utilizing the <script setup>
method to define props:
<script setup lang="ts">
const props = defineProps({
classes: String,
label: String,
})
</script>
This also gives a warning about the unused props
variable. Although this isn't major, the initial error persists.
Implementing a setup
method within my component:
setup(props) {
defineProps({
classes: String,
label: String,
})
},
Adopting the traditional way of defining props with overzealous type declarations:
export default defineComponent({
name: "AppStory",
props: {
label: {
type: String as PropType<string>,
required: true,
},
},
A more conservative approach with type definitions:
export default defineComponent({
name: "AppStory",
props: {
label: {
type: String,
required: true,
},
},
Does anyone have a successfully functioning Single File Component (SFC) in Vue3 that effectively utilizes properties? What am I missing here? Most examples I come across either lack props or don't incorporate TypeScript. The documentation for Vue3 doesn't focus much on TypeScript, and the examples provided do not seem to address this rather fundamental scenario.