Utilizing Vue and TypeScript - Retrieving a Variable Declared in the Data() Method within Another Method

I recently made the switch to using Vue3 with TypeScript after previously working with Vue2 and JavaScript. I am encountering an issue in my IDE where it is showing an error (even though the code itself functions correctly, but may not be entirely accurate).

Here is the code snippet:

export default {
  name: 'Sidebar',
  data() {
    return {
      menu: { name: 'Menu', icon: MenuIcon },
      navigation: [
        { id: 0, name: 'Home', icon: HomeIcon, path: '/', count: 0, current: true },
        { id: 1, name: 'Users', icon: UsersIcon, path: '/about', count: 3, current: false },
      ]
    }
  },
  methods: {
    makeCurrent: function(item: navItem) {
      this.navigation.forEach((nav: { current: boolean; id: any; }) => {
        nav.current = nav.id === item.id;
      })
    }
  }
}

The specific error highlighted by the IDE is on the usage of "navigation" in this.navigation.forEach(..., which results in the following error message:

TS2339: Property 'navigation' does not exist on type '{ makeCurrent: (item: navItem) => void; }'

Answer №1

To implement TS inference in a .vue component effectively, it is recommended to enclose the

export default { ...options }

within the defineComponent method.

Here is an example:

import { defineComponent } from "vue";

export default defineComponent({
  name: 'Sidebar',
  data() {
    return {
      menu: { name: 'Menu', icon: MenuIcon },
      navigation: [
        { id: 0, name: 'Home', icon: HomeIcon, path: '/', count:0, current: true },
        { id: 1, name: 'Users', icon: UsersIcon, path: '/about', count: 3, current: false },
      ]
    }
  },
  methods: {
    makeCurrent: function(item: navItem) {
      this.navigation.forEach((nav: { current: boolean; id: any; }) => {
        nav.current = nav.id === item.id;
      })
    }
  }
});

Additional Note: In vue.js 2, you can also utilize the defineComponent method by incorporating the https://github.com/vuejs/composition-api plugin.

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

When trying to access the DOM from another module in nwjs, it appears to be empty

When working with modules in my nwjs application that utilize document, it appears that they are unable to access the DOM of the main page correctly. Below is a simple test demonstrating this issue. The following files are involved: package.json ... "ma ...

The Vue Router triggers the beforeDestroy method for the parent component whenever there is a change in the child routes

My route configuration looks like this: { path: '/menu', component: () => import('./Menu.vue'), children: [ { path: 'admin', component: () => import('./menus-admin/MenusAdmin.vue'), name: 'm ...

The union type consisting of String, Boolean, and Number in type-graphql has encountered an error

I attempted to create a union type in type-graphql that represents the String, Number, and Boolean classes, but unfortunately, it was not successful. Does anyone have any suggestions on how to achieve this? export const NonObjectType = createUnionType({ ...

The designated function name can be either "onButtonClick" or "onClickButton"

I am a Japanese developer working on web projects. Improving my English language skills is one of my goals. What would be the correct name for a function that indicates "when a button has been clicked"? Is it "onButtonClick"? Maybe "onClickButton"? Co ...

Place the token within the Nuxt auth-module

Working on a project using the Nuxt auth-module. The Login API response is structured like this: data:{ data:{ user:{ bio: null, createdAt: "2021-06-29T12:28:42.442Z", email: "<a href="/cdn- ...

Encountering "Invalid hook call" error with React Router while integrating Higher Order Components for authentication

Dealing with an error: React Router shows "Invalid hook call" with higher-order components for authentication Dilemma I have developed two distinct approaches for authentication wrappers in my React components with React Router. The first method functions ...

The Vue Multiselect component fails to properly update the {{ value }} when using v-model

I am currently implementing Vue Multiselect "^2.0.0-beta.14" within Laravel 5.3. You can find the example at https://github.com/monterail/vue-multiselect/tree/2.0#install--basic-usage The plugin is rendering properly, but I am facing issues in updating th ...

Having trouble accessing previously submitted form values in Angular

When I try to update the form, I notice that my meetupform.controls.day array is not retaining the previously selected values app.component.html <div *ngIf="meetupForm.controls.recurring.value==='weekly'"> <mat-checkbox (change)="o ...

Encountering an error while utilizing the Vue router

Every time I implement the vue-router in my Vue project let router = require('vue-router'); Vue.use(router); I encounter this error message: Error: TypeError: plugin.apply is not a function The issue resolves once I remove the router implemen ...

Simplified method for utilizing plugins with the composition api in vue 3

When incorporating vuex or vue-router as plugins in Vue and utilizing the options API, access to these plugins can be achieved using the this keyword. main.js import { createApp } from 'vue'; import i18n from '@/i18n'; import router fr ...

What is the most efficient way to dynamically load a script file before proceeding with the rest of the code execution?

In my Angular home.component.ts file, I have added the script loading code as shown below: export class HomeComponent { constructor() { this.loadDynamicScript(); } public loadDynamicScript() { var script = document.createElement(&a ...

What is the best way to include keys in my JSON data, rather than just values?

I've encountered an issue with the PrimeVue datatable I created, as it is only showing empty rows. After investigating, I believe the problem lies in my JSON data structure, where the fields do not have keys. What modifications should be made to stan ...

ionChange - only detect changes made in the view and update the model in Ionic 2

In my Ionic 2 application, I have a feature that allows users to schedule notifications as reminders. The requirements for this feature are as follows: Upon entering the reminder page, it should check if there is a saved reminder. If a reminder is saved ...

Is there a way to assess Python code within a document's context using JavaScript in JupyterLab?

When using Jupyter Notebooks, I can create a cell with the following JavaScript code: %%javascript IPython.notebook.kernel.execute('x = 42') After executing this code, in another cell containing Python code, the variable x will be bound to 42 a ...

React TSX file not recognizing JSON data stored in an HTML data attribute

I am having some trouble with implementing the password toggle component from the Preline UI. Here is how the component looks: "use client" import React, { ChangeEvent, MouseEventHandler, useEffect } from "react"; export default functi ...

What is the best method for showcasing a nested JSON value?

I need to show the data for the month of April. Here is the code snippet: {{my_dates['2018-04-23']}} This code displays: { "april":0, "may":0, "june":0, "july":0, "august":0, "september":0, "october":0, "income_trips":" ...

Incorporating Dynamic Events into HTML Generated on the Fly within a Vue.js Component

Currently, I am facing an issue where I am trying to dynamically generate HTML in a Vue.js component. While I have successfully rendered the HTML, I am struggling to connect the events for these dynamically generated elements. To illustrate this problem, I ...

Using Typescript to test with Karma, we can inject a service for our

I'm currently experiencing a problem with running tests in my application. I recently transitioned to using TypeScript and am still in the learning process. The specific error I'm encountering is: Error: [$injector:unpr] Unknown provider: movie ...

The value of 'Boolean' cannot be changed as it is a constant or a read-only property and cannot be assigned

I've been working on creating a TypeScript object to handle read/write permissions in my application, but I'm stuck on an issue with variable assignment that doesn't make sense to me. Any help or guidance would be greatly appreciated. expor ...

Angula 5 presents a glitch in its functionality where the on click events fail

I have successfully replicated a screenshot in HTML/CSS. You can view the screenshot here: https://i.stack.imgur.com/9ay9W.jpg To demonstrate the functionality of the screenshot, I created a fiddle. In this fiddle, clicking on the "items waiting" text wil ...