Passing properties from the parent component to the child component in Vue3JS using TypeScript

Today marks my inaugural experience with VueJS, as we delve into a class project utilizing TypeScript. The task at hand is to transfer the attributes of the tabsData variable from the parent component (the view) to the child (the view component). Allow me to present you with the code snippet:

<script setup lang="ts">
//import { reactive, ref, computed } from "vue";
import ArgumentTabComponent from "./components/ArgumentTabComponent.vue";
import $t from "@/core/utils/i18n/translate";
import Button from "primevue/button";
import type { IntArgumentListData } from "./types/IntArgumentListData";

const tabsData: IntArgumentListData[] = [
  {
    title: "Argumento 1",
    content: "texto1",
  },
  {
    title: "Argumento 2",
    content: "texto2",
  },
  {
    title: "Argumento 3",
    content: "texto3",
  },
  {
    title: "Argumento 4",
    content: "texto4",
  },
  {
    title: "Argumento 5",
    content: "texto5",
  },
];

const handleRedirect = () => {
  alert("Aceptando!");
};
</script>

<template>
  <br />
  <h1>Argumentarios</h1>
  <div class="">
    <ArgumentTabComponent> {{ tabsData }}</ArgumentTabComponent>
    <hr />
    <Button :label="$t('common.accept')" @click="handleRedirect" />
  </div>
</template>

Extensive research on the internet and YouTube failed to provide much insight due to the use of export default {} being incompatible with TypeScript. In an attempt to pass properties, I employed the following approach:

<script setup lang="ts">
import TabView from "primevue/tabview";
import TabPanel from "primevue/tabpanel";

// Lib imports
//import { ref } from "vue";
import type { IntArgumentListData } from "../types/IntArgumentListData";

// Properties
const props = defineProps<{
  title: IntArgumentListData;
  content: IntArgumentListData;
}>();
</script>

<template>
  <br />
  <div class="">
    <TabView>
      <TabPanel v-for="tab in props" :key="tab.title" :header="tab.title">
        <p>{{ tab.content }}</p>
      </TabPanel>
    </TabView>
  </div>
  <br />
</template>

Unfortunately, this method resulted in a perplexing error within the parent component:

error in parent component

Facing this challenge has left me disoriented. Despite countless hours dedicated to experimentation and contemplation, I am unable to decipher my missteps. Your assistance is greatly appreciated.

Error message in English:

The type '{ tabData: IntArgumentListData[]; "tab data": IntArgumentListData[]; }' cannot be assigned to type 'IntrinsicAttributes & Partial<{}> & Omit<Readonly<ExtractPropTypes<__VLS_TypePropsToRuntimeProps<{ tabsData: IntArgumentListData[]; }>>> & VNodeProps & AllowedComponentProps & ComponentCustomProps, never>'. Property "tabsData" is missing in type "{ tabData: IntArgumentListData[]; "tab-data": IntArgumentListData[]; }", but is required in type "Omit<Readonly<ExtractPropTypes<__VLS_TypePropsToRuntimeProps<{ tabsData: IntArgumentListData[ ]; }>>> & VNodeProps & AllowedComponentProps & ComponentCustomProps, never>".ts(2322)

Answer №1

Your props have been defined as shown below:

const props = defineProps<{
  title: IntArgumentListData;
  content: IntArgumentListData;
}>();

This implies that you are creating two props - one named title with a type of IntArgumentListData, and another named content also with a type of IntArgumentListData.

In your definition of IntArgumentListData, you have already specified the properties title and content.

Therefore, what you may want to do is something like this:

const props = defineProps<{
  tabsData: IntArgumentListData[];
}>();

Then in your component, you only need to iterate over the tabsData array.

NOTE: While using defineProps, the props will be accessible directly in the template without using props.tabsData; but in the script setup section, you need to access it using props.tabsData

<TabPanel v-for="tab in tabsData" :key="tab.title" :header="tab.title">

By doing this, the prop will be available on the component when used within the parent component. You will then need to bind the data to the prop when calling the component.

<ArgumentTabComponent :tab-data="tabsData" />

Useful documentation references:


Could you please provide an English translation of the error message?

The translated version might look something like this:

<script setup lang="ts">
//import { reactive, ref, computed } from "vue";
import ArgumentTabComponent from "./components/ArgumentTabComponent.vue";
import $t from "@/core/utils/i18n/translate";
import Button from "primevue/button";
import type { IntArgumentListData } from "./types/IntArgumentListData";

const tabsData: IntArgumentListData[] = [
  {
    title: "Argument 1",
    content: "text1",
  },
  {
    title: "Argument 2",
    content: "text2",
  },
  {
    title: "Argument 3",
    content: "text3",
  },
  {
    title: "Argument 4",
    content: "text4",
  },
  {
    title: "Argument 5",
    content: "text5",
  },
];

const handleRedirect = () => {
  alert("Accepting!");
};
</script>

<template>
  <br />
  <h1>Arguments</h1>
  <div class="">
    <ArgumentTabComponent :tabs-data="tabsData" />
    <hr />
    <Button :label="$t('common.accept')" @click="handleRedirect" />
  </div>
</template>

Child:

<script setup lang="ts">
import TabView from "primevue/tabview.vue";
import TabPanel from "primevue/tabpanel.vue";

// Lib imports
//import { ref } from "vue";
import type { IntArgumentListData } from "../types/IntArgumentListData";

// Properties
const props = defineProps<{
  tabsData: IntArgumentListData[];
}>();
</script>

<template>
  <br />
  <div class="">
    <TabView>
      <TabPanel v-for="tab in tabsData" :key="tab.title" :header="tab.title">
        <p>{{ tab.content }}</p>
      </TabPanel>
    </TabView>
  </div>
  <br />
</template>

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

Utilize the useState hook to update state when changes occur in the

I currently have a functional component that utilizes a useState hook. The values it holds are sourced from my redux store, and I aim to update the state with the new store state every time an action is dispatched. At the moment, I've manually set an ...

Having difficulty casting the parameter type from Array.find() in TypeScript

In my codebase, I am dealing with the OrganisationInterface type: export declare interface OrganisationInterface { documents?: { [documentType: OrganisationDocumentTypesList]: { // enum id: string; name: string; ...

Angular - Error: Cannot read property 'publishLast' of undefined

My goal is to prevent multiple requests from being created when using the async pipe. I am facing an issue with a request to fetch a user from the API: getUser() { this._user = this.http.get<User>(environment.baseAPIUrl + 'user') ...

The v-validate feature in Vue.js seems to be encountering issues when used in conjunction with

Why is 'v-validate' not functioning correctly in vue.js with <multiselect> when I submit the form using v-on:submit.prevent='fun()'? <div class="select-inp"> <multiselect v-model="selectedShifts" tra ...

"Error: The angularjs code is unable to access the $http variable within

$http({ url: "php/load.php", method: "GET", params: {'userId':userId} }).success(function(data, status, headers, config) { $scope.mydata = data; mydata = data; }).error(function(data, status, headers, config) { }); It's puzzling why ...

Is there anything else I should attempt in order to fix this npm start error?

I have been troubleshooting this issue by researching other stack overflow posts, but I continue to encounter the same error message repeatedly. My goal is to execute a Javascript program that incorporates ReactJS. Initially, everything was functioning sm ...

When `strictNullChecks` is turned on, how does the `void` type differ from the `undefined` literal type?

When strictNullChecks is turned on: (u: undefined, v: void, n: null) => { v = u; u = v; // type error: Type 'void' is not assignable to type 'undefined' v = n; // type error: Type 'null' is not assignable to type &ap ...

Guide on transferring control from a successful jQuery event to an HTML form

I am currently using the following jQuery code to validate user details. $.ajax({ type: "POST", url: "Login", data:'uname='+encodeURIComponent(uname)+'&'+'pass='+encodeURIComponent(pass), ...

Error: The parent selector "&" cannot be used in top-level selectors. $::webkit-input-placeholder

I am facing an issue while trying to run a legacy create-react-app that utilizes Sass. Initially, when I ran npm start, I encountered the error 'Cannot find module sass', which resembled the message found in this stack overflow post. To resolve t ...

Issue with Vue @Watch not properly recognizing changes in a boolean value

I'm currently experimenting with watch functions in vue-ts. I have configured a watch function that is supposed to trigger whenever a Boolean variable's value changes, but for some reason, it's not triggering at all and I'm unable to de ...

How come the mongoose ref feature is not functioning properly for me when I attempt to reference objects from a different schema?

I'm having trouble accessing the attributes of a store's address, as I keep getting 'undefined'. It seems that the address is only an id, even though I set up a 'ref' in the address schema. What could be causing this issue? H ...

FabricJS Canvas with a React DropDown Feature

While I have successfully created a TextBox on FabricJS Canvas, creating a Dropdown component has proven to be a challenge. The fabric.Textbox method allows for easy creation of text boxes, but no such built-in method exists for dropdowns in FabricJS. If y ...

What is the best way to highlight and extract only the white-coded texts on VSCode to facilitate the process of translating webpages manually?

Currently, I'm engaged in a project where my task involves duplicating an entire website using HTTrack. However, I only need to copy the main page and web pages that are one link deep. Upon copying the website, my next challenge is to translate all of ...

Mapping custom colors to paths in D3 Sunburst visualizations can add a vibrant and unique touch

Currently, I am in the process of developing a D3 Sunburst Vue component and utilizing the npm package vue-d3-sunburst for this purpose. To access the documentation for the package, please visit: https://www.npmjs.com/package/vue-d3-sunburst The document ...

What could be causing the bootstrap 4 col-md-3 block to shrink when using position fixed?

When working with Bootstrap 4, I encountered an issue where changing the block position from relative to fixed using a script caused the block to decrease in size. The script I used includes a .sticky class: .sticky { position: fixed !important; top: ...

Failed to execute test suite in React and Jest framework

While working on updates for our existing project, I encountered an error that is causing some of the tests to fail: FAIL src/components/changelog/__test__/ChangeLogOverView.test.tsx ● Test suite failed to run TypeError: Cannot create property & ...

Is there a way to establish a connection between two excel entries using Angular?

In order to connect xlsx file records with their corresponding ids using angular, I am seeking a solution. To elaborate further: Let me provide an example for better understanding: Scenario 1 https://i.stack.imgur.com/25Uns.png Scenario 2 https://i ...

Extracting information from JSON using jQuery

this is a sample json object: { "box 1": [{ "difficulty_grade": "5a+" }, { "gym": "New_gym" }, { "route_author": "some author" },]} Here is the code snippet: variable groups contains JSON data as shown in the image. for (var k in groups){ $p ...

What could be the reason for Angular to merge the element at index 0 of an array into a subarray instead of doing

After setting up the Array in my oninit function, I encountered an issue where one part of the array was functioning as intended while the other returned an error. this.tests = [{ status: 0, testresults: [{ name: 'test ...

Ionic3 footer using ion-tabs

Is there a way to create a common footer for all pages with 5 buttons, where the first button is selected by default? The page opened by this first button should have three tabs. I have already created the tabs but am unsure how to add the footer without r ...