I am trying to bring my props into my component. Found this documentation: https://vuejs.org/guide/typescript/composition-api.html#typing-component-props which is referenced close to everywhere. Obviously I should put my type into the defineProps function.
<script setup lang="ts">
const props = defineProps({
foo: { type: String, required: true },
bar: Number
})
props.foo // string
props.bar // number | undefined - they are not usable in the template if I just define the const...
</script>
So I tried to put them to my component. But to do so I need to do sth within the setup.
import { defineComponent } from 'vue'
export default defineComponent({
props: {
message: String
},
setup(props) {
props.message // <-- type: string
}
})
<template>
<CNavItem :href="props.href">
<CIcon customClassName="nav-icon" :icon="icon" />{{label}}</CNavItem>
</template>
<script lang="ts">
import { defineComponent, defineProps } from "vue";
import { CNavItem } from '@coreui/vue';
import { CIcon } from '@coreui/icons-vue';
interface Props {
label: string;
href: string;
icon: any[];
}
const props = defineProps<Props>();
export default defineComponent({
components: {
CNavItem,
CIcon
},
setup(props) {
// I need to do sth with props here I guess, but I do not know how to get it to my template.
// If I don't the compiler will complain...
}
});
</script>
I think I have a missig link somewhere here. So how would I get my content of const props
into my template?
CodePudding user response:
It seems to me that you have mixed the two ways.
Have you tried to do as below?
import { defineComponent } from 'vue'
export default defineComponent({
// type inference enabled
props: {
label: String,
href: String,
icon: any[]
},
setup(props) {
props.label // ...
// ...
}
})
See the link.
CodePudding user response:
defineProps
can only be used inside <script setup>
(ts
or js
).
In the example you posted, you're trying to use it inside a <script>
tag's root (does not have the setup
attribute!), where it won't work.
To clarify:
<script setup lang="ts">
syntax:
<script setup lang="ts">
defineProps({
foo: Number
})
</script>
<template>
<div>{{ foo }}</div>
</template>
<script lang="ts">
syntax:
<script lang="ts">
export default {
props: {
foo: Number
}
}
</script>
<template>
<div>{{ foo }}</div>
</template>
See them working here.