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

The problem with the onClick event not triggering in Angular buttons

My issue revolves around a button in my code that is supposed to trigger a function logging the user out. However, for some reason, the event associated with it doesn't seem to be functioning at all. Here's the relevant code snippet: TS File: imp ...

How can an additional value be sent to the form validation method?

I have created a form group like this: import { checkPasswordStrength } from './validators'; @Component({ .... export class PasswordComponent { ... this.userFormPassword = this.fb.group({ 'password': ['', [ ...

Exploring nuxtServerInit for Handling API Requests

I am currently utilizing nuxt.js along with Firebase as my API source. Utilizing the nuxtServerInit method, I am able to fetch all of my products from the Firebase API in one go. With just 3 categories and around 20 products, the API request remains relati ...

Typescript encounters an overload error on the Accumulator argument while using reduce operation

I encountered the following code snippet: const foo = ( fields: { [key: string]: string, } ) => { const { one, two } = Object.values(fields).reduce( (acc, field) => { if (isOne(field)) { return { ...acc, two: [...acc.two, ...

v-if causing inability for bootstrap dropdown to expand

Encountered a strange issue with a v-if statement in relation to a sidebar dropdown menu. Essentially, I am trying to hide the dropdown menu based on user permissions. The problem arises when the v-if statement is added - the dropdown menu fails to work pr ...

Can a specific v-bind class be activated without affecting others in VueJS and Laravel?

In my project, I have several input fields with a specific class that is triggered if the value is less than 0. Each input field functions similarly to the example below. However, I am facing an issue where when one input triggers the class, all input fi ...

Need at least one of two methods, or both, in an abstract class

Consider the following scenario: export abstract class AbstractButton { // Must always provide this method abstract someRequiredMethod(): void; // The successor must implement one of these (or both) abstract setInnerText?(): void; abst ...

Decomposing a Vuex module into distinct files with Nuxt: A step-by-step guide

In the official Nuxt documentation (here), it is mentioned that 'You can choose to divide a module file into separate files: state.js, actions.js, mutations.js, and getters.js'. While there are examples of breaking down the Vuex store at the roo ...

Utilize a Typescript library within a separate Typescript library

I have a TypeScript library on GitHub that I want to install using npm install --save git+ssh://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f38362b1d15c3f4">[email protected]</a>:User/mylib.git into my targ ...

Utilizing Nodemailer and ReadableStreams to send email attachments stored in S3

My current challenge involves sending emails with Nodemailer that include attachments hosted in S3, utilizing JS AWS SDK v3. The example provided in the Nodemailer documentation demonstrates how to send an attachment using a read stream created from a file ...

The 'target' property is not found on the specified 'string' type

I've encountered an issue while creating a search bar in Typescript. Despite my efforts, the input is not being recognized. It seems that whenever I use the term 'target' in my onChange method, it triggers an error stating: Property &ap ...

How to identify alterations in user input within Angular?

I need assistance with my search input functionality. I want to ensure that the this.searchProperties.emit is only triggered when the user interacts with the input field by touching it or making an input. The current issue is that the emit function gets ca ...

Guide to setting up .env Variables on a DigitalOcean Ubuntu droplet

After deploying my Node.js app on a DigitalOcean Ubuntu droplet, I encountered the need for variables from my .env file. How can I go about creating these variables within the DigitalOcean droplet? ...

Unable to retrieve a property from a variable with various data types

In my implementation, I have created a versatile type that can be either of another type or an interface, allowing me to utilize it in functions. type Value = string | number interface IUser { name: string, id: string } export type IGlobalUser = Value | IU ...

Tips for preventing a specific component from being cached with Nuxt.js keep-alive props

I am facing some challenges with the Nuxt.js keep-alive property. My goal is to cache all components except one, and reload dynamic data again. However, all components seem to be cached and I can't seem to figure out what I'm doing wrong. Is this ...

Handlebar files are not compatible with Typescript loading capabilities

I am encountering an issue with my directory structure as follows : src |- server |- myServer.ts |- views |- myView.hbs dist |- server |- myServer.js The problem lies in the fact that the dist folder does not have a views subfolder, where the J ...

Exploring Angular 9: Experimenting with iterating over a collection of objects and performing validations

Forgive me if this is a basic question, but I am new to Angular 9 and json. I am attempting to iterate through a list and only create a table row if the correct ID matches the ID passed from the previous page link. I am struggling to make the if statement ...

having difficulty sending a post request with Angular

Submitting form data via HTTP post will look like this: saveDataFile(mutlidata,id,value): Observable<Response> { var _url = 'http://xxxx.xxx.xxx'; var saveDataURL = _url + '/' + id; var _this = this; ...

Is it possible to locate a Typescript class only when there are no references to its properties?

Currently, I am utilizing TypeScript 2.0 within VSCode and although the highlighted errors are being confirmed by the TypeScript compiler, they all point to a module that I am importing: import * as els from 'elasticsearch'; The module elastics ...

Vue 2 AOT before-the-fact compilation

Trying to grasp the concepts of Vue here. As someone who has experience with Angular 2, I'm curious to know if the documentation provided by Vuejs 2 is similar to Angular 2's AOT: With vue-loader or vueify, templates within *.vue files get pre ...