Obtain the Vue Class Component Decorator's method within a Watcher

My question is similar to the ones raised in this and this GitHub issue, but unfortunately they were closed without a solution.

I am working with Vue and TypeScript using Vue Class Components. I need to access a method of my Vue class from inside a watcher defined in the @Component decorator. While I know how to access data using this.$data, I'm not sure how to access methods in this context.

Although my code works during runtime, it generates compilation errors and issues in Visual Studio Code ("Property 'clearInfo' does not exist on type 'Vue'.");

@Component({
  watch: {
    firstMesh(newMesh) {
      if (newMesh === undefined) this.clearInfo(1);   // this leads to errors
      else this.showMeshInfo(newMesh, 1);
    },
    secondMesh(newMesh) {
      if (newMesh === undefined) this.clearInfo(2);
      else this.showMeshInfo(newMesh, 2);
    },
  },
})


export default class Info extends Vue {
  clearInfo(whichMesh : number) {
...
  }

  showMeshInfo(mesh : any, index : number) {
    ....
  }


}

Answer №1

There are two approaches you can take:

  1. Include the watch functions in the class definition itself
// To begin, install vue-property-decorators using npm i -S vue-property-decorator
// This library offers useful decorators. More information can be found here: https://github.com/kaorun343/vue-property-decorator

import { Vue, Component, Watch } from 'vue-property-decorator'


@Component
export default class Info extends Vue {
  @Watch('firstMesh')
  public watchFirstMesh(newValue) {
     // ... perform necessary actions with newValue here
  }

  @Watch('secondMesh')
  public watchSecondMesh(newValue) {
     // ... perform necessary actions with newValue here
  }
}
  1. Define the watches and methods within the options part of @Component
@Component({
  watch: {
    firstMesh(newMesh) {
      if (newMesh === undefined) this.clearInfo(1);   
      else this.showMeshInfo(newMesh, 1);
    },
    secondMesh(newMesh) {
      if (newMesh === undefined) this.clearInfo(2);
      else this.showMeshInfo(newMesh, 2);
    },
  },
  methods: {
   clearInfo(whichMesh : number) {
     ...
   },
   showMeshInfo(mesh : any, index : number) {
     ....
   }   
  }
})
export default class Info extends Vue {
  public clearInfo!: (wichMesh: number) => void;
  public showMeshInfo!: (mesh: any, index: number) => void;
}

Explanation

  1. The detailed explanation can be found in the provided links

  2. When defining options within the decorator @Component({...}), they are accessible when the class is instantiated. TypeScript might not infer all available elements automatically, so explicit declarations like

    public clearInfo!: (whichMesh: number) => void;
    are required to inform the compiler. For clarification on syntax, refer to the links provided below:

public clearInfo!: (whichMesh: number) => void;

The ! operator signifies non-null assertion. It indicates to the compiler that the expression cannot be null or undefined at that point.

The function signature (whichMesh: number) => void; denotes a function expecting a number argument (whichMesh) and returning void.

Non-null assertion in TypeScript Function signatures in TypeScript

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

Launching a peek inside a modal using AngularJS through a service

Feeling a bit unsure about my approach... I'm diving into my first AngularJS app and trying to grasp the architecture. So, I've built a service called isAjax, utilizing the $http module to handle API calls for me. I'm capturing the succes ...

I'm encountering an issue with automatically updating content on a webpage

I am currently working on a webpage that refreshes its content automatically to display the most up-to-date data from the database. Here's the JavaScript code I'm using: setInterval(function() { $("#status").load('refresh.php'); }, ...

An improved method for generating a jQuery selection

I developed a custom plugin to extract a specific segment of a collection: jQuery.range = function(start, end, includingTheLast) { var result = $([]), i = 0; while (!this.eq(i).is(start) && i < this.length) i++; for (; i & ...

Combine functions from two objects that share the same properties into an array for each property

I need help combining the methods from two objects into one, resulting in an array of methods for each property in the parent object: obj1 = {"prop1":"method1","prop2":"method2"} obj2 = {"prop1":"method3","prop2":"method4"} Expected result: obj1 = {"pro ...

Recognition of the ng-click function in Ionic buttons can occasionally be unreliable

I am experiencing an issue with my Ionic app that wraps a web-app using Angular. Within the app, there are buttons coded like this: <ion-view view-title="Orders"> <ion-content scroll="true" overflow-scroll="true"> <div class="row"> ...

What is the process for including a checkbox with a label in Card Media?

I attempted to create this feature using code. However, I encountered an issue where the CardMedia and the checkbox would not align properly, resulting in a lack of responsiveness. <Card> <CardMedia ...

Step-by-step guide on reading a text file in a Nuxt 3 project located within a specific

I'm currently working on reading a file named data.txt in my nuxt 3 application, located in the src/resources/data.txt folder. However, when the app is built, it tries to read the file from .output/src/resources/data.txt Is there a way to read a file ...

Animation not properly synced with Bootstrap 4 Dropdown hide event

Could you please check out my codepen for clarification: http://codepen.io/anon/pen/oLZOyp Essentially, I have integrated two animations using animate.css into Bootstrap 4 show.bs.dropdown and hide.bs.dropdown events. The animations work on the first show. ...

A nested DragSource component within a parent DragSource component in React DnD

In my project, I am working with a tree structure that consists of a root "Tree" component containing a list of root "TreeNodes". Each TreeNode can have an arbitrary number of children. Within the render method of the TreeNode component, I iterate over th ...

Using ReactJS to return a component from a function

Working with React, useState, and React-Icons. I am trying to implement a dropdown menu without using Bootstrap. My goal is to change the icon upon clicking to trigger a function, but currently, it only displays the raw SVG details. Any suggestions on how ...

Ways to grab the outermost element when a click event happens

When I click on a div, I want to retrieve the innermost element like so: <div id="show_trash_id" class="switch switch-xs"> <input type="checkbox"/> <span class="slider round"> <span cl ...

Converting timestamps: Retrieve day, date, hour, minutes, etc. without utilizing the "new Date()" function

Currently developing a web-app and faced with the challenge of displaying items in a list correctly. I am working on converting the timestamp attached to each item into a readable format. For instance, 1475842129770 is transformed into Friday, 07.09.2016 ...

Receiving a "Undefined index" error while passing information to a PHP script via jQuery

I have extensively researched this issue, including reading numerous StackOverflow questions, but I am still unable to find a solution. My problem involves retrieving the 'id' attribute value of an HTML 'a' element with jQuery when the ...

Having difficulty installing npm on Mac m1 with Monterey operating system

npm install npm ERR! code ENOENT npm ERR! syscall open npm ERR! path /Users/ahmed/package.json npm ERR! errno -2 npm ERR! enoent ENOENT: no such file or directory, open '/Users/ahmed/package.json' npm ERR! enoent This issue is likely due to npm n ...

Tips for keeping Fancybox from deleting the selected thumbnail

New to using fancybox and running into some issues.. starting to regret adding it. I have a row of thumbnails, all good, but when I click one it opens the THUMBNAIL instead of the actual link and on top of that, it DELETES the thumbnail from the DOM. I tr ...

The issue of 'position: fixed' not properly functioning within the Materialize CSS modal

My goal is to have the header of the Modal stay fixed while scrolling, but for some reason, the option position:fixed; is not working. I am currently using Materialize CSS to build the modal and surprisingly, position:sticky; is working. $(document).rea ...

Issue with Bootstrap 4 nested collapse: "data-parent" attribute malfunctioning

I'm looking to implement the collapse data-parent options in a way that mimics traditional accordion behavior: all collapsible elements under a specified parent should close when a new one is opened. However, I am encountering issues with this setup. ...

Ensure that test cases in Angular2 include a line that covers conditions for returning values

I'm having trouble implementing test coverage for an online platform, as I'm not sure how to approach it. Within my service method, I have the following code: public getResults() { return this.http(url,body).map(this.mapResponse); } private ...

Is there a way to determine if a collapsed navbar is currently open?

My Bootstrap 4 navbar collapses on mobile, and I'm looking to detect when it opens and closes. Is there a way to achieve this? Thank you! ...

Is there a way to convert a JSON input object to a model class using TypeScript in a Node.js application?

Currently, I am developing my Node.js server using TypeScript and the express framework. Here is an example of what my controller and route looks like: export class AuthController { public async signUpNewUser(request: Request, response: Response) { ...