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

Unable to connect to Alpine store from an external source due to a typescript error

Here is how I have configured my Alpine store: Alpine.store( 'state', ({ qr: '' })) Now, I am attempting to update it from an external source as follows: Alpine.store( 'state' ).qr = 'test' However, I am encounte ...

Tips for maintaining the active state of an item within a component that loops through a dataset

I am working with an array of objects (specifically, posts represented as strings) and I am looking to be able to edit each one individually. However, I am encountering an issue where clicking on the edit button triggers editing for all posts at once: co ...

Guide to Conditionally Importing a Module in Angular

I am currently developing a module for Search integration. Instead of directly importing the SearchModule inside my app.module.ts file, I would like to implement a method where an API is called and the SearchModule is imported based on the API response. @N ...

Resolving NestJS Custom Startup Dependencies

In my setup, I have a factory responsible for resolving redis connections: import {RedisClient} from "redis"; export const RedisProvider = { provide: 'RedisToken', useFactory: async () => { return new Promise((resolve, reject ...

Using ternary operator to set multiple variables in setState

Conditional Operator for Setting State in React I am wondering if there is a way to set the state with a variable that holds the correct state value using setState method. interface state { isfiltered: array<boolean> } this.setState({ ...

Error: Unable to access null properties while attempting to address Readonly property error by implementing an interface

Here is the code snippet I am working with: interface State { backgroundColor: boolean; isLoading: boolean; errorOccured: boolean; acknowledgment: string; } export class GoodIntention extends React.Component<Props, State> { ... onCli ...

Using Typescript and ThreeJS, include new elements to the environment within the loader

Can someone help me with the following code snippet? export class LandingPageComponent implements OnInit { scene: THREE.Scene; (...) ngOnInit() { this.scene = new THREE.Scene(); var loader = new THREE.JSONLoader(); loader.load("../../assets/fire_lion.j ...

Guide on showing a dropdown menu depending on the data in the current array index within a table

I am working with an object array that I want to display in a table. My goal is to have a dropdown select if the 'validvalues' field is not empty. How can I achieve this so that each row in the table has different options from the array? When &ap ...

Using `new Date(device.timestamp).toLocaleString()` in React with typescript results in an invalid date

The timestamp I am receiving is in unix time format. {devices.map((device, index) => { return ( <tr key={index} className="bg-white border-b "> <td className="py-4 px-6"> {getSensor ...

What is the best way to set up TypeScript interfaces using predefined string literals to limit the possible data types for shared attributes?

In this scenario, we have two interfaces named A and B with validation and variant properties. The goal is to create an Example object by using only the variant and validation values provided (since field is already defined). However, I encountered an erro ...

TypeScript combines strong typing for arrays into a unified array of objects

I developed a JavaScript function that can merge multiple arrays into an array of objects based on provided key names. Here’s an example: const mergeArraysToSeries = (arrs, keys) => { const merged = []; for (let dataIndex = 0; dataIndex < arrs ...

Tips for assigning a JSON object as the resolve value and enabling autosuggestion when utilizing the promise function

Is there a way to make my promise function auto-suggest the resolved value if it's a JSON object, similar to how the axios NPM module does? Here is an example of how axios accomplishes this: axios.get("url.com") .then((res) => { Here, axios will ...

Create a new WebSocket package for Node.js that allows for segregating connections into

I am currently exploring ways to implement a feature similar to "rooms" using the npm 'ws' package, inspired by how rooms function in socket.io. I want to avoid using socket.io, but I am faced with the challenge of retrieving user/room informatio ...

Is it possible to enable autocomplete for JavaScript generated code in .proto files?

I recently created a basic .proto file with the following content: syntax = "proto3"; message Event { optional string name = 1; } After downloading and installing the protoc linux compiler (protoc-3.19.3-linux-x86_64.zip) on my local machine, ...

difficulty updating data values with $emit on a Vue object

Utilizing $emit to facilitate communication between a child and parent component. A method in the child component triggers the $emit at different stages of an api call. For instance, before initiating the api call, certain values need to be sent to the par ...

Overriding a shared module service in Angular from a separate module: A step-by-step guide

I am working with various modules such as SchoolModule, UniversityModule, and SharedModule The SharedModule includes a BaseService that both the SchoolModule and UniversityModule providers are utilizing as an extension When loading the SchoolModule, I ne ...

Is it possible for TypeScript to automatically determine the specific type that was used in a union type parameter?

I need some help with a utility function I'm working on that can remove a specified number of elements from either a string or an array. My goal is to have the compiler determine whether the return value should be a string or an array based on what is ...

An unfamiliar data type is provided as a number but is treated as a string that behaves like a number

Here is the code snippet in question: let myVar = unknown; myVar = 5; console.log((myVar as string) + 5); Upon running this code, it surprisingly outputs 10 instead of what I expected to be 55. Can someone help me understand why? ...

The power of Vue reactivity in action with Typescript classes

Currently, I am working on a Vue application that is using Vue 2.6.10 along with Typescript 3.6.3. In my project, I have defined a Typescript class which contains some standard functions for the application. There is also a plugin in place that assigns an ...

I am disappointed with the lack of functionality in Angular's HTML type inference

When working inside an Angular component, I want to select a div element by id or class. This method works menuDisplayDiv = document.getElementsByClassName("some_class")[0] as HTMLDivElement; menuDisplayDiv = document.getElementById("some ...