Search code examples
typescriptvuejs3vue-componentquasar-frameworkquasar

Vue3 Typescript props either show error or nothing at all


I am trying to use the default Quasar card component to show data coming from props. However nothing ever shows up in my component and i get a bunch of different errors depending on what I try.

Latest ones were "TypeError: Cannot read properties of null (reading 'character')" and "defineProps() is a compiler-hint helper that is only usable inside of a single file component. Its arguments should be compiled away and passing it at runtime has no effect"

What exactly am I doing wrong here?

<template>
<q-card class="my-card" flat bordered>
    <q-card-section horizontal>
      <q-img class="col-5" src="https://cdn.quasar.dev/img/parallax2.jpg" />
      <q-card-section> {{ props.character }} </q-card-section>
    </q-card-section>
  </q-card>
</template>
<script lang="ts">
import { defineComponent, defineProps, PropType } from 'vue';
import { Character } from './models';

export default defineComponent({
  name: 'CardComponent',

  setup() {
    const props = defineProps({
      character: Object as PropType<Character> | null,
    });
    return {
      props,
      lorem: 'Lorem ipsum dolor sit amet, blah blah blah',
    };
  },
});
</script>
<style lang="sass" scoped>
.my-card
  width: 100%
  max-width: 350px
</style>

Solution

  • defineProps() is used in SFC script setup. When you are using object syntax with a setup() function, props are passed as the first argument to setup() and defined using the props property.

    So it should look something like this:

    export default defineComponent({
      name: 'CardComponent',
      props: {
        character: Object as PropType<Character> | null,
      },
      setup(props) {
        return {
          props,
          lorem: 'Lorem ipsum dolor sit amet, blah blah blah',
        };
      },
    });