How to pass props to a Vue component in TypeScript setup but not using them

Trying to incorporate props into my component has led me to this documentation: https://vuejs.org/guide/typescript/composition-api.html#typing-component-props, which seems to be a common reference point. The type should be included in 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>

I attempted to add them to my component. However, it requires some action within the setup block.

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) {
        // Need to figure out how to pass props into the template here.
        // Otherwise, compiler will raise errors...
    }
});
</script>

Somewhere along the way, there seems to be a missing link. How can I ensure that the content of const props is accessible in my template?

Answer №1

defineProps is designed to be used exclusively within the context of <script setup> in either ts or js.
The code snippet you shared demonstrates an attempt to utilize it outside of the proper environment, specifically within a root level <script> tag without the required setup attribute.


To provide further clarity:

  • Syntax using
    <script setup lang="ts">
    :
<script setup lang="ts">
defineProps({
  foo: Number
})
</script>
<template>
  <div>{{ foo }}</div>
</template>
  • Syntax using
    <script lang="ts">
    :
<script lang="ts">
export default {
  props: {
    foo: Number
  }
}
</script>
<template>
  <div>{{ foo }}</div>
</template>

For functional examples, please refer to this resource.

Answer №2

It appears that there may have been a mix-up with the methods you are using.

Have you attempted to follow the steps below?

import { defineComponent } from 'vue'

export default defineComponent({
  // utilizing type inference
  props: {
    label: String,
    href: String,
    icon: any[]
  },
  setup(props) {
    props.label // ...
    // ...
  }
})

Refer to this link.

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

Incorporating VueJS into a complex WebForms project with multiple pages

I'm currently working on a webforms project and I would like to incorporate VueJS into it. However, I am facing challenges when trying to set up the root element. If I enclose my content within a <div id="app"></div> element and specify t ...

"Exploring the method of fetching data from an API in Vue.js router and passing it along

axios.get('http://127.0.0.1:8000/api/filter-trip?fromlocation='+this.form.from_place+'&tolocation='+this.form.to_place+'&assign_date='+DatabaseFormat+'',auth) .then(response => { ...

Ways to sort through a Unix timestamp

Recently, I encountered an issue with my Ionic mobile application. It has a search button and filter feature that works well for filtering words. However, the problem arises when it comes to filtering dates displayed in the app as timestamps using Angular ...

Encountering issues with utilizing global variables in Ionic 3

Using Ionic 3, I created a class for global variables but encountered an error Uncaught (in promise): Error: No provider for Globals! Error: No provider for Globals! at injectionError (http://localhost:8100/build/vendor.js:1590:86) at noProviderError Th ...

Utilize TypeScript to bind React-Redux decorator with a stateful component

I have developed an illustrative component called Hello where I made sure to utilize appropriate types for the props and state, all while incorporating the connect decorator from React-Redux. If you are interested, you can explore the details in the GitHu ...

Angular - Implementing selective binding in a function

In my current Angular project, I am utilizing Datatables and buttons to manipulate data. The buttons available are "View", "Mark as completed", and "Mark as incomplete" which trigger specific functions when clicked. To achieve this functionality, the follo ...

Adding Profile Photos to Authenticated User Accounts in Firebase / Ionic: A Step-By-Step Guide

I have thoroughly gone through the Firebase Docs on "Managing Users" for web along with watching their instructional video on YouTube. Despite following the code they provide, I am encountering an error message that states: "Property 'afAuth' do ...

The attribute cannot be found within the string or object typescript

Encountering the error: Property 'p' does not exist on type 'string | { p: string; }'. Can someone assist me in resolving this issue? interface x{ n:string | {p:string} } function text(args:x){ const {n:{p}}=args; console.l ...

Guide to accessing state in Vuex using a getter from one module to another module

I've been working on an application using VueJS, but I'm facing some challenges with Vuex modules. No matter what I try, I can't seem to access the state in a module when calling it from another module. When I check my Vue Devtools Vuex ge ...

Utilize Angular2 to automatically fill dynamic forms with default data retrieved from an API

After spending a few weeks working with Angular 2, I am currently tackling the task of creating dynamic forms for a system settings page. The objective is to have the API return multiple forms, construct these forms within tabs, incorporate various types o ...

Preventing Directive Angular 2 from Triggering Stop Button Click Event

I created my application using angular 2 and PrimeNG. I am trying to implement directives for checking user authority when a button is clicked. The issue I am facing is that even though there is no authority, the click event continues to be triggered. How ...

Automatically create the web.config file upon executing the command "npm run build"

My Vue app is hosted on IIS. In order to follow the instructions here, I need a custom web.config file in the dist folder. The issue I am facing is that whenever I run "npm run build", the entire dist folder gets deleted, including my web.config file. I th ...

Exploring the seamless connection between Vue Storefront and Shopify

I am currently attempting to connect Vuestorefront with Shopify but I am struggling to comprehend the correct approach. Out of all the available repositories, there are several options such as Vue Storefront for front end here, Vue Storefront API for back ...

When trying to access a specific property of an object in Typescript using a key that is defined as a subset of

UPDATE: Take a look at the revised solution below, inspired by @GarlefWegart's input. I've been exploring the creation of generic typings for dynamic GraphQL query outcomes (mostly for fun, as I suspect similar solutions already exist). I' ...

Utilizing vue.js router guards with asynchronous user information retrieval

Currently, I am developing a Vue.js application that requires the implementation of router guards to restrict access based on user roles and prevent unauthorized users from accessing the application. The login process involves integrating an external appli ...

Only load the value in ref when it is specifically requested in Vue

Within my Vue project, I am utilizing a ref variable that stores data retrieved from a database. This reference is contained within Pinia's setup store for easy access. The objective is to load the data only when requested by the user and then always ...

Utilize the identical element

Incorporating the JwPaginationComponent into both my auction.component and auctiongroup.component has become a necessity. To achieve this, I have created a shared.module.ts: import { NgModule } from '@angular/core'; import { JwPaginationCompon ...

Setting up a variable with no operation assigned to it

As I delved into the Angular utils source code, I stumbled upon this interesting line: export const NOOP: any = () => {}; It seems pretty straightforward - a variable that doesn't perform any operation. But then, within the same library, there is ...

Utilizing *ngFor to display elements with odd indices

Within my Angular application, I have successfully used a loop to populate the 4 employeeList components. Here is the code snippet: <div *ngFor="let record of records"> <p-panel> <div comp-employeeList [listFilter]="record.Filte ...

Learn how to pass the rel attribute value from a clicked image to a method using Vue.js

I'm currently delving into vue.js and I've encountered a challenge. I want to pass the value of a rel attribute from an image to a method, but so far I have been unsuccessful. Here is the HTML code snippet: <template> <div> ...