Vue3 with Typescript may either display an error message or remain empty when handling props

I've been attempting to utilize the default Quasar card component in order to display data received from props. Unfortunately, I haven't had any success as my component remains empty and I keep encountering various errors with each attempt.

Recently, I've come across errors such as "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".

Can someone help me figure out what mistake I'm making 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>

Answer №1

defineProps() is commonly utilized within SFC script setup. In scenarios where object syntax is employed with a setup() function, props are typically passed as the initial argument to setup() and declared through the props property.

The structure should resemble something similar to 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',
    };
  },
});

Answer №2

I agree with Moritz's answer, but if you encounter any difficulties, here is a straightforward example of the Quasar framework's Parallax component utilizing props without PropType.

const props = { message: "This text will display using {{ props.message  }} " };
const app = Vue.createApp({
  props: ["message"],
  setup() {
    return {
      props,
      name: "Quasar Framework"
    };
  }
});

app.use(Quasar, { config: {} });
app.mount("#q-app");
<script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0677736775677446342837342834">[email protected]</a>/dist/quasar.umd.prod.js"></script>
<link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet">

<div id="q-app" style="min-height: 100vh;" data-message="This text won't show, neither will line #7.">
  <div class="q-pa-md">
    {{message}}
    <q-parallax>
      <template v-slot:media>
        <img src="https://cdn.quasar.dev/img/parallax2.jpg" style="opacity: .75 ">
      </template>

      <template v-slot:content="scope">
        <div class="absolute column items-center" :style="{
            opacity: 0.75 + (1 - scope.percentScrolled) * 0.55,
            top: (scope.percentScrolled * 60) + '%',
            left: 0,
            right: 0
          }">
          <img src="https://cdn.quasar.dev/logo-v2/svg/logo-mono-white.svg" style="width: 150px; height: 150px">
          <div class="text-h3 text-purple-5 text-center">{{ name }} </div>
          <div class="text-h4 text-center text-green-6">{{ props.message }}</div>
          <div class="text-h6 text-orange-3 text-center">
            v{{ $q.version }}
          </div>
        </div>
      </template>
    </q-parallax>
  </div>
</div>

If the code doesn't work or show Parallax on Stack Overflow, check out this codepen:

Link to Codepen

Edit: Additionally, here is the complete code including the assumed Character model that I tried to get working in the Vue playground:

<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 { QCard } from 'quasar';
import { defineComponent, defineProps, PropType } from 'vue';

interface Character {
  name: string
}

// you can try this way as well
// const props = defineProps({
//   character: Object as PropType<Character>
// })
export default defineComponent({
  name: 'CardComponent',
  props: {
    character: Object as PropType<Character>
  },
  components: {
  QCard
  },
  setup(props) {
    return {
      props,
      lorem: 'Lorem ipsum dolor sit amet, blah blah blah',
    };
  },
});
</script>
<style scoped>
.my-card {
  width: 100%;
  max-width: 350px;
}
</style>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Angular's dependency injection in a project that has been transpiled with Babel

I am currently attempting to transpile my Angular 6 project, which is written in TypeScript, using the new Babel 7. However, I am facing challenges with getting dependency injection to function properly. Every time I try to launch the project in Chrome, I ...

"Encountering issues when trying to retrieve a global variable in TypeScript

Currently facing an issue with my code. I declared the markers variable inside a class to make it global and accessible throughout the class. However, I am able to access markers inside initMap but encountering difficulties accessing it within the function ...

The closeOnClickOutside feature seems to be malfunctioning in the angular-2-dropdown-multiselect plugin

I'm currently using 2 angular-2-dropdown-multiselect dropdowns within a bootstarp mega div. The issue I'm facing is that when I click on the dropdown, it opens fine. However, when I click outside of the dropdown, it doesn't close as expected ...

Transform the object into an array of JSON with specified keys

Here is a sample object: { labels: ["city A", "city B"], data: ["Abc", "Bcd"] }; I am looking to transform the above object into an array of JSON like this: [ { labels: "city A", data: "Abc" }, { labels: "city B", data: "Bcd" }, ]; ...

Error: Module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef' does not export 'ProSidebar' as requested

Using the pro-side-bar library in React is causing an issue for me. When I run the code, the console shows the following error using the dev tools: Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef& ...

A data type labeled as 'undefined' needs to include a method called '[Symbol.iterator]()' which will then return an iterator

I've been working on converting my reducer from JavaScript to TypeScript, but I keep encountering a strange error that I can't seem to resolve. The issue arises when I attempt to use ellipsis for array deconstruction in the reducer [...state.mess ...

After using apt to install tsc, I find myself in a dilemma on how to either delete or upgrade it

After realizing I was missing Typescript on my server, I attempted to run the 'tsc' command. However, I received a message suggesting I use 'apt install tsc' instead. Without much thought, I executed the command. Normally, I would insta ...

Asynchronous NestJs HTTP service request

Is there a way to implement Async/Await on the HttpService in NestJs? The code snippet below does not seem to be functioning as expected: async create(data) { return await this.httpService.post(url, data); } ...

Angular allows for the dynamic updating of og meta tags

Sharing dynamic content on WhatsApp has been made possible through an API. By utilizing the angular Meta class in my component.ts file, I am able to dynamically update the default meta tag property in index.html with the latest content. ...

Ways to incorporate extension methods through a "barrel file" - how to do it?

When attempting to define extension methods in separate files and import them through a barrel file, the methods don't seem to be added to the prototype. The following approach works: import './rxjs-extensions/my-observable-extension-1'; i ...

An issue occurred while trying to use a function that has a return type of NextPage

After successfully implementing the code below: const HomePage: NextPage = () => ( <div> <div>HomePage</div> </div> ); I wanted to adhere to Airbnb's style guide, which required using a named function. This led me t ...

What could be causing Vue Material dialogs to frequently slide off the screen?

I am currently utilizing a dialog feature from Vue Material (). After following the link and opening the first custom dialog on the page, I noticed that it tends to shift towards the top left of my screen, making only a portion of the dialog visible. This ...

Encountered a problem with AngularUniversal prerendering: UnhandledPromiseRejectionWarning: Unable to locate NgModule metadata for 'class{}'

Objective The task may seem lengthy, but it's straightforward! Currently, I am utilizing Angular Universal for Server-Side Rendering (SSR) by following a tutorial. The Universal/express-engine has been installed, main.js is generated in the dist/pro ...

Clearly defining the data types for static dictionary values, while also deducing the precise structure or at least the keys

My goal is to create a static dictionary that is defined as a single object literal. I want to: Specify the type of values explicitly for typechecks and IDE suggestions Still have the ability to infer the exact shape, or at least keys I can achieve the f ...

ngClass with multiple conditions

I am currently working on implementing the following functionality - I have two pre-set classes that are combined with some component variables successfully. However, I now need to include an additional conditional class. Although the first part is functi ...

What is the best practice for preloading route data before navigating to the route?

When preparing to render a page for a specific route, my goal is to fetch the necessary data synchronously first. Ideally, I prefer to handle the data fetching within the page component, but I am open to doing it in the router files as well. I have experim ...

Check out the attributes of a class

I have a TypeScript class that is defined like this: export class MyModel { ID: number; TYPE_ID: number; RECOMMENDED_HOURS: number; UNASSIGNED_HOURS: number; } In a different .ts file, I instantiate this class within a component: export class My ...

Can we verify if strings can serve as valid property names for interfaces?

Let's consider an interface presented below: interface User { id: string; name: string; age: number; } We also have a method defined as follows: function getUserValues(properties:string[]):void { Ajax.fetch("user", properties).then( ...

Is there a way to incorporate several select choices using specific HTML?

I am currently trying to dynamically populate a select tag with multiple option tags based on custom HTML content. While I understand how to insert dynamic content with ng-content, my challenge lies in separating the dynamic content and wrapping it in mat ...

Numerous toggle classes available

Having the following HTML inside a <span> element: <span (click)="openLeft()"></span> A method in a @Component sets a boolean variable like so: private isOpen: boolean; openLeft() { this.isOpen = !this.isOpen; } To toggle classes ...