What could be causing the malfunction of getter/setter in a Vue TypeScript class component?

Recently delving into the world of vue.js, I find myself puzzled by the unexpected behavior of the code snippet below:

<template>
  <page-layout>
    <h1>Hello, Invoicer here</h1>
    <form class="invoicer-form">
      <div><label><span>Datum</span><input v-model="date" v-on:change="dateChanged" /></label></div>
      <div><label><span>Zeitraum</span><input v-model="timespan" /></label></div>
    </form>
  </page-layout>
</template>

<script lang="ts">
    import { Component, Prop, Vue } from 'vue-property-decorator'
    import PageLayout from '@/components/layout/PageLayout.vue'
    import dayjs from 'dayjs'
    import customParseFormat from 'dayjs/plugin/customParseFormat'

    @Component({
        components: { PageLayout }
    })
    export default class Invoicer extends Vue {
        
        date = ''
        _timespan = ''

        beforeCreate(): void {
            dayjs.extend(customParseFormat)
        }

        dateChanged(): void {
            const format = 'DD.MM.YYYY'
            const date = dayjs(this.date, format)
            if (date.isValid()) {
                if (!this.timespan) {
                    const from = date.subtract(1, 'month').startOf('month').format(format)
                    const until = date.endOf('month').format(format)
                    this.timespan = `${from} - ${until}`
                }
            }
        }

        get timespan(): string {
            return this._timespan
        }

        set timespan(value: string) {
            this._timespan = value
        }

    }
</script>

After modifying the 'Datum', the dateChanged() method is called to update the _timespan property using its setter. Interestingly, the changes are not reflected in the GUI. When I bypass the setter/getter and directly access the _timespan property, everything functions flawlessly. Is it expected for the setter/getter or computed property to behave in this manner?

Answer №1

Great news! I managed to get it up and running. The issue was that the specified class doesn't actually exist during runtime. Instead, the vue-class-component plugin utilizes the definition to create a VueComponent. This means that this isn't exactly what it appears to be. The plugin adds properties as data properties and getter/setter as computed properties. Interestingly, it seems to skip properties that start with an underscore. As mentioned by Owl in a comment, this behavior is not specific to vue-class-component but is a documented feature of Vue: https://v2.vuejs.org/v2/api/#data Regardless, making a simple adjustment to the code made it work:

    @Component({
        components: { PageLayout }
    })
    export default class Invoicer extends Vue {

        date = ''
        timesspan = ''

        beforeCreate(): void {
            dayjs.extend(customParseFormat)
        }

        dateChanged(): void {
            console.log("badsfls")
            const format = 'DD.MM.YYYY'
            const date = dayjs(this.date, format)
            if (date.isValid()) {
                if (!this.timespan) {
                    const from = date.subtract(1, 'month').startOf('month').format(format)
                    const until = date.endOf('month').format(format)
                    this.timespan = `${from} - ${until}`
                }
            }
        }

        get timespan(): string {
            return this.timesspan
        }

        set timespan(value: string) {
            this.timesspan = value
        }

    }

Renaming the property without an underscore prefix did the trick.

However, I've decided to part ways with the vue-class-component plugin. It introduced too much complexity for my taste.

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

Exploring how to iterate through an object to locate a specific value with TypeScript and React

I am looking to hide a button if there is at least one order with status 'ACCEPTED' or 'DONE' in any area or subareas. How can I achieve hiding the "Hide me" menu item when there is at least one area with orders having status 'ACCE ...

tips for utilizing a variable for inferring an object in typescript

In my current code, I have the following working implementation: type ParamType = { a: string, b: string } | { c: string } if ('a' in params) { doSomethingA(params) } else { doSomethingC(params) } The functions doSomethingA and doSomething ...

How to identify generic return type in TypeScript

My goal is to develop a core dialog class that can automatically resolve dialog types and return values based on the input provided. I have made progress in implementing this functionality, but I am facing challenges with handling the return values. Each ...

Using Typescript in the browser with Babel and Webpack: Step-by-Step Guide

I've been exploring the use of Typescript in my browser with a specific architecture: Typescript in browser architecture However, I'm facing an issue with the import/export functionality when running this command: tsc && babel build-ts -d lib && ...

Unexpectedly, a significant ngrx createEffect leads to an unusual error following an update, but the issue vanishes when certain code snippets like tap or filter are disabled

I have been in the process of upgrading a massive Angular 12 project to Angular 13 and have completed several steps. One significant change was the rewriting of Effects using a newer approach like createEffect(() => instead of @Effect However, during ...

Angular 8: Implementing Form Validation with a Boolean Flag

Within my HTML code, I have a function (change)="limitUser($event)". In Typescript, I utilize a for loop to iterate through each element and determine if the value is less than 10. If it exceeds 10, the inValid = true condition is set. All form fields in m ...

I am attempting to send an array as parameters in an httpservice request, but the parameters are being evaluated as an empty array

Trying to upload multiple images involves converting the image into a base64 encoded string and storing its metadata with an array. The reference to the image path is stored in the database, so the functionality is written in the backend for insertion. Ho ...

What is the best way to implement a sliding animation for a toggle button?

Currently, I am working on a toggle bar element that is functioning correctly in terms of styling the toggled button. However, I would like to add more animation to enhance the user experience. The concept is to have the active button slide to the newly s ...

Associate keys with strings and then map them to a specific type of strings in Typescript

I am endeavoring to develop a React component that extends the Octicons icon library available from Github at @githubprimer/octicons-react. One of the components exported by the library is the iconsByName type, which has the following structure: type ico ...

Upon hovering, icons for each project name are displayed when `mouseenter` event is triggered

My issue lies with the mouseenter function. I am trying to display icons specific to the project name I hover over, but currently, it displays icons for all projects at once. I want each project hovered over to show me its respective icons Below is some c ...

Angular BreakPointObserver is a powerful tool that allows developers

Hey there! I've been working with the BreakpointObserver and have run into an issue while trying to define breakpoints for mobile and tablet devices. It seems that my code is functioning properly for tablets, but not for mobile devices. Upon further i ...

What methods can be used to accurately display the data type with TypeOf()?

When working with the following code: const data = Observable.from([{name: 'Alice', age: 25}, {name: 'Bob', age: 35}]); console.log(typeof(data)); The type is displayed as Object(). Is there a way to obtain more specific information? ...

The Angular application is receiving a 404 error when trying to access the .NET Core

Having trouble calling a method in the controller via URL, as I keep encountering a 404 error. What could be the issue? API Endpoint: http://localhost:5000/Home/HomeTest /*.net core web-api*/ namespace MyApp.Controllers { Route("api/[controller]") ...

Having an excess of 32 individual byte values

My current project involves developing a permission system using bitwise operators. A question came up regarding the limitation of having only 32 permissions in place: enum permissions { none = 0, Founder = 1 << 0, SeeAdmins = 1 << ...

Avoiding repeated axios calls

In my VueJS app, I have been using axios to make API calls. However, I noticed that in every component, I am repeating the same code to check if the user has clicked a button before sending the request. To solve this issue, I came up with a function called ...

Angular 6 Calendar Template issues with parsing: Unable to link to 'view' as it is not recognized as a valid property of 'div'

I am in the process of developing an application that utilizes this angular calendar. My tech stack includes Angular 6 with AngularFire2 and Firebase. Below is my app.module.ts file: import { BrowserModule } from '@angular/platform-browser'; imp ...

Creating a TypeScript client to interact with React components integrated within an ASP.NET MVC web application

Can we automatically generate a TypeScript client to handle data transfer between a React component and an ASP.NET MVC controller? We have a TypeScript React app that communicates with an ASP.NET Core Web API using NSwag for TypeScript client generation. ...

methods to obfuscate a document while storing it in a different directory (vue.js)

I need assistance with obfuscating my server.js file and storing it in the dist directory within a subfolder named server. Currently, I am utilizing the CopyWebpackPlugin. new CopyWebpackPlugin([ { from: path.resolve(__dirname, '../static' ...

Guide to Setting Up "Remember Me" Login for Users in Angular

I am having trouble setting the 'Remember Me' option on my Login page. I tried using localstorage session but it seems like something is missing in the service file that's causing it not to respond properly. I attempted to follow a guide on ...

Error TS2322: The function expecting a type of 'FormEventHandler<HTMLFormElement>' cannot be assigned the type '(data: TicketFullDTO) => Promise<void>'

I am currently working on creating an edit form to modify data from a database based on its ID. Here is my approach: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material-ui/core/TextField" ...