Utilizing getters and setters with v-model in a class-based component: A step-by-step guide

Transitioning from an angular background to vuejs has been challenging for me as a newbie. I've encountered issues while trying to bind setter/getter in v-model for an input field. Interestingly, when I directly bind it to a variable, everything works just fine.

Here is the code snippet that reflects my approach:

The TypeScript file for My Component:

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

@Component({
    components: {}
})
export default class MyComponent extends Vue {
    private _username: string = '';
    private _password: string = '';

    get username(): string {
        return this._username;
    }

    set username(value: string) {
        this._username = value;
    }

    get password(): string {
        return this._password;
    }

    set password(value: string) {
        this._password = value;
    }

    public login() {
        console.log(this.username, this.password);
    }
}

The Vue file for MyComponent:

<template>
    <form @submit.prevent="login">
        <v-text-field
                v-model="username"
                label="Username"
                required>
        </v-text-field>
        <v-text-field
                v-model="password"
                :type="'password'"
                label="Password"
                required>
        </v-text-field>
        <v-btn large type="submit">Login</v-btn>
        <v-btn large>Reset</v-btn>
    </form>
</template>

Despite initializing the variables with empty strings, I'm still unable to see the values of username and password displayed in the console upon typing into the input fields. Instead, all I get is undefined undefined. The documentation hasn't been much help either, especially since I'm using typescript with vue-class-component. Any guidance on how to resolve this issue would be greatly appreciated.

Answer №1

Source

Vue instances do not proxy properties starting with _ or $, to avoid conflicts with internal properties and API methods. To access them, use vm.$data._property.

To fix this issue, simply avoid using the _ prefix.

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

@Component({
    components: {}
})
export default class MyComponent extends Vue {
    private xusername: string = '';
    private xpassword: string = '';


    get username(): string {
        return this.xusername;
    }

    set username(value: string) {
        this.xusername = value;
    }

    get password(): string {
        return this.xpassword;
    }

    set password(value: string) {
        this.xpassword = value;
    }

    public login() {
        console.log(this.username, this.password);
    }
}

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 methods of simulating properties using jest.fn()

Here is the code snippet I'm currently working with: this.$vs.loading() .... this.$vs.loading.close() To successfully pass a mock to shallowMount, I have set it up as follows: const vs = { loading: jest.fn() } mocks: { $vs: vs } However, the ...

Is it possible for vue-resource to send a cross-domain POST request directly?

When developing my frontend using vue.js, I run it on http://localhost:8080 with the command npm run dev. For the backend, I utilize flask and have it running on http://localhost:8081. To handle crossdomain issues in Flask, I implemented a decorator: (C ...

There seems to be a mismatch in this Typescript function overloading - None of the over

Currently, I am in the process of developing a function that invokes another function with enums as accepted parameters. The return type from this function varies depending on the value passed. Both the function being called (b) and the calling function (a ...

Ways to modify this request in order to update the current status

How can I optimize these calls to avoid repeating the same sentence for refreshing the state? I'm not looking for a major overhaul, just some suggestions like putting this call inside a function and invoking it when needed... export const CategoriesPa ...

The error message "Type 'string | number' is not assignable to type 'number'" indicates a type mismatch in the code, where a value can be either

I encountered an error code while working with AngularJS to create a countdown timer. Can someone please assist me? //Rounding the remainders obtained above to the nearest whole number intervalinsecond = (intervalinsecond < 10) ? "0" + intervalinseco ...

Indicate the location of tsconfig.json file when setting up Cypress

Having trouble integrating Cypress with Typescript? I've encountered an issue where Cypress is unable to locate the tsconfig.json file I created for it. My preference is to organize my project with a custom directory structure, keeping configuration f ...

Incorporate the pdfmake.js file into my TypeScript file

Working on a VSTS web extension and looking to utilize PDFmake.js to generate a pdf. The PDFmake.js file needs to be imported into the node_nodules folder by running npm install pdfmake. To import this JavaScript file into my TypeScript file, I'm fol ...

Stop the execution of client-side code in a Nuxt SSR web application

After setting up a SSR/progressive nuxt project using create-nuxt-app, I encountered an issue with HTTP requests being made from my two pages to a backend API. These requests are initiated from the async asyncData(ctx) method in my nuxt page. Strangely, w ...

Click event to verify, delete, and include class identifier in angular13

Looking to enhance functionality by dynamically adding and removing the 'active' class to 'li a' elements on click. While the current code performs well when clicking from top to bottom, it fails to work in reverse order. component.htm ...

What is the process for retrieving an element from component interaction?

Is there a way to dynamically change the background color based on component interaction? I am looking for a method to compare the target element with the current element. For example, here is a hypothetical scenario: <span [style.background]=" ...

Steer clear of using inline styling when designing with Mui V5

I firmly believe that separating styling from code enhances the clarity and cleanliness of the code. Personally, I have always viewed using inline styling (style={{}}) as a bad practice. In Mui V4, it was simple - I would create a styles file and import i ...

Whenever the return condition is false, make sure to subscribe to the Angular CanActivate Guard

In my UserAccessGuard class, I have a method that captures the current path and compares it to the user's available paths. However, I am facing asynchronous problems because the condition inside the subscribe block causes my Hasaccess variable to rema ...

Distinguishing Routes for Administrators and non-Administrators in Laravel

I am currently developing a Single Page Application (SPA) using Laravel and Vue. My goal is to have two separate routes for admin and non-admin users, as shown below. // For Admin Route::any('admin/{any}', static function () { return view(&a ...

Mismatch between generic types

When working with this code, I encounter a syntax error at m1 and m2. The error message states: Type 'T' is not assignable to Type 'boolean' or Type 'T' is not assignable to Type 'string' interface customMethod { ...

`How can I effectively test a React.js page utilizing both Context and useEffect?`

I'm struggling with testing a page that uses Context and useEffect with Jest and Testing-library, can you offer any assistance? REPOSITORY: https://github.com/jefferson1104/padawan Context File: src/context/personContext.tsx import { createContext, ...

What is the best way to show/hide group items in a PrimeNG dropdown menu?

Is it possible to show or hide group items when clicking on the group header if the group contains items? For instance, I would like to display 3 items (AA, BB, CC) in a dropdown menu. The first 2 options (AA and BB) should be selectable, but when I click ...

Is there a way to determine if a React functional component has been displayed in the code?

Currently, I am working on implementing logging to track the time it takes for a functional component in React to render. My main challenge is determining when the rendering of the component is complete and visible to the user on the front end. I believe t ...

I'm facing a challenge with Firebase rules regarding user configurations that should enable read and write access. How can I overcome this hurdle?

Currently, I am logged into my application using GoogleAuthProvider and in my browser as [email protected] The rules for my app project are set up like this: In one of the views, there is a toggle that triggers a setDoc function. However, when I us ...

Submit user-specific form data in Angular 5 based on user selection

Utilizing a common reactive form to handle various types of user data, such as teachers, students, guards, etc. The form is selected from a dropdown list. The goal is to send specific data objects based on the selected user type. A model named "User" has ...

Typescript: Implementing a generic function with the flexibility of an optional parameter

Having some difficulty writing a generic function with an optional parameter type Action<TParameters = undefined> = (parameters: TParameters) => void const A: Action = () => console.log('Hi :)') // This works as expected const B: ...