How to assign a value to a component variable using props in Vue.js

I am attempting to assign a props value to my component variable. Below is the code I'm working with:

export default {
    props: {
        // eslint-disable-next-line vue/require-default-prop
        multiPaginatedTableTitle: {
            type: String,
            required: false
        },
        // eslint-disable-next-line vue/require-default-prop
        lists: {
            type: Array,
            required: false
        }
    },
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    data: function(): any {
        return {
            selectedList: this.lists[0]
        };
    },
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    created: function(){
        this.selectedList = this.lists[0];
    },
    methods: {
        // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
        changeSelectedItems: function(index: string){
            const newSelectedList: any = this.lists.find((x: { index: string; }) => x.index == index);
            if (newSelectedList != undefined) {
                this.selectedList = newSelectedList;
            }
        }
    }
};

However, I encounter an error:

Property 'lists' does not exist on type '{ props: { multiPaginatedTableTitle: { type: StringConstructor; required: boolean; }; lists: { type: ArrayConstructor; required: boolean; }; }; data: () => any; created: () => void; methods: { ...; }; }'.

I have come across suggestions that this could be related to type inferences and can potentially be resolved by using defineComponent (refer to stackoverflow: how to fix the error : Property 'X' does not exist on type '{ object }'. I attempted to implement defineComponent with the following code but did not achieve significant results:

import defineComponent from 'vue';

export default new defineComponent({
    props: {
        // eslint-disable-next-line vue/require-default-prop
        multiPaginatedTableTitle: {
            type: String,
            required: false
        },
        // eslint-disable-next-line vue/require-default-prop
        lists: {
            type: Array,
            required: false
        }
    },
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    data: function(): any {
        return {
            selectedList: this.lists[0]
        };
    },
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    created: function(){
        this.selectedList = this.lists[0];
    },
    methods: {
        // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
        changeSelectedItems: function(index: string){
            const newSelectedList: any = this.lists.find((x: { index: string; }) => x.index == index);
            if (newSelectedList != undefined) {
                this.selectedList = newSelectedList;
            }
        }
    }
});

If anyone knows how I can resolve this issue, I would greatly appreciate your help.

Thank you for your time.

Answer №1

To avoid the error, consider changing 'required: false' to 'default: () => []'. Additionally, during the created() hook, props may not be accessible, so try using mounted() instead.

Answer №2

Encountered this issue some time back, seems to be related to how the data function's scope is defined. To fix this problem, make sure your data function is structured like this:

export default {
    ...

    data() {
        return {
            ....
        }
    },

    ...
}

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

In Typescript, interfaces are required to have properties written in Pascal Case instead of camel Case

Currently, I am facing a strange issue in my ASP.NET 5 application where I am using Angular 1.4 with TypeScript and RXJS. Somehow, during the runtime, all my interface properties are getting converted from camel casing to Pascal casing. This unexpected beh ...

What is the reason for not hashing the password in this system?

My password hashing code using Argon2 is shown below: import { ForbiddenException, Injectable } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { AuthDto } from './dto'; import * as arg ...

Issue "unable to use property "useEffect", dispatcher is undefined" arises exclusively when working with a local npm package

I am currently in the process of creating my very own private npm package to streamline some components and functions that I frequently use across various React TypeScript projects. However, when I try to install the package locally using its local path, ...

Refreshing Vue components based on changed data using asynchronous methods

In my application, there is an icon that represents a favorite or not favorite status with either a red or white heart. The code snippet below shows how the image source changes based on the favorite status: <img :src="favoriteStatus ? '/icon ...

Guide to incorporating code coverage in React/NextJs using Typescript (create-next-app) and cypress

I initiated a fresh project using create-next-app with the default settings. npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="365544535742531b58534e421b57464676070518021801">[email protected]</a> --- Would you l ...

Encountering a service call error during the execution of Angular 2 unit tests using Jasmine

Struggling with testing an angular service, my TypeScript code seems correct but I keep getting an error in my test cases for "this.someFunction.show()" not being a function, even though it exists in my actual service. Here is what I'm attempting to d ...

Guide on developing a dynamic Navbar component on Laravel Mix with Vue Js

As I delve into learning and practicing Vue.js, my goal is to create a component that includes elements like Navbar and Footer within a single view. Initially, I set up an index for the first view but faced an issue with adding the navbar as it did not sho ...

What is the process for dynamically inserting a new object into an array of data objects in Vue.js?

I am a beginner with vue.js and currently working on a form. I have an add button in my form, so when the user clicks on it, the same form field will be added to the form. Users can add as many times as they want. Here is my initial data: data () { ret ...

Is it possible to rotate an image with a random angle when hovering in Angular?

I'm currently working on a photo gallery project and my goal is to have the images rotate when hovered over. However, I am experiencing difficulties in passing values from TypeScript into the CSS. HTML <div class="back"> <div cl ...

What steps can be taken to ensure that the requestAnimationFrame function does not redraw the canvas multiple times after a button click?

I am currently working on a project where I am drawing a sin wave on a canvas and adding movement to it. export class CanvasComponent implements OnInit { @ViewChild('canvas', { static: true }) canvas: ElementRef<HTMLCanvasElement>; ...

What should be the proper service parameter type in the constructor and where should it be sourced from?

Currently, I am faced with a situation where I have two Angular 1 services in separate files and need to use the first service within the second one. How can I properly type the first service in the constructor to satisfy TypeScript requirements and ensure ...

What is the method to access the information within the observer?

When I receive the data from the observer in the console, here is what I see: https://i.stack.imgur.com/dVzwu.png However, I am only interested in extracting this specific data from each item on the list: https://i.stack.imgur.com/g8oHL.png To extract ...

Leverage the power of the MEAN stack with Angular 2 to seamlessly retrieve data from multiple APIs

Using angular2, nodejs, expressjs, and mongodb for development. I need all APIs to fetch data and display it on an HTML page. Below is the code snippet from my .ts file. view image description here All APIs have been tested and are s ...

A guide to using the up and down keys to switch focus between div elements in a react component with TypeScript and CSS

I am currently working with a scenario where data is being displayed within different div elements, and I wish to enable the selection/focus of a specific div when users use the up/down arrow keys. While trying to achieve this functionality by using refs ...

Integrating Vue Router with a CFML (Lucee) server

I have a Vue Router set up that is working flawlessly for navigation using <router-link to="/test">test</router-link>, but when I manually type the URL into the browser like , it reloads the page and shows a 404 error. On the server-side, I ...

Enhancing an array item with Vuex

Is there a way to change an object within an array using Vuex? I attempted the following approach, but it was unsuccessful: const state = { categories: [] }; // mutations: [mutationType.UPDATE_CATEGORY] (state, id, category) { const record = state. ...

Is there a way to incorporate the "Handoff to Human" feature in a Microsoft Teams bot app by utilizing the Teams Toolkit? Can this functionality be implemented using TypeScript?

Can someone assist me with figuring out how to incorporate the "handoff conversation to human agent mechanism" in my project using TypeScript, Microsoft Bot Framework, and Teams Toolkit? ...

Exploring ways to simulate an event object in React/Typescript testing using Jest

I need to verify that the console.log function is triggered when the user hits the Enter key on an interactive HTMLElement. I've attempted to simulate an event object for the function below in Jest with Typescript, but it's not working as expecte ...

This object does not have support for the attribute or method "getAttribute"

I've searched for solutions, but nothing seems to work for me and now I'm feeling quite lost. My current setup involves Cordova, Ionic, and Angular 2. Below is the HTML snippet: <ion-col *ngFor="let value of myButtonsFirstRow" width-25> ...

Upgrade to Angular 12: TypeScript is now an essential requirement for the Angular Compiler

Recently, I made sure to update my project to the latest Angular version. After running "ng update", I received a confirmation that everything was already up to date, indicating that all required packages had been successfully updated in the last step of t ...