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

What is the process for defining an opaque type in programming?

[ This is not this ] Take a look at this snippet of code: interface Machine<OpaqueType> { get(): OpaqueType, update(t: OpaqueType); } const f = <U, V>(uMachine: Machine<U>, vMachine: Machine<V>) => { const u = uMach ...

Determining when props are updated in Vue.js 2 when passing an object as a prop

Let's say there is an array feedsArray, with a sample value like this: this.feedsArray = [ { id: 1, type: 'Comment', value: 'How are you today ?' }, { id: 2, type: 'Meet', name: 'Daily ...

When implementing JSS with React and TypeScript, certain CSS properties may encounter a `type is unassignable` error

Recently delving into TypeScript, I've encountered an issue within my project that was created using create-react-app with TypeScript and incorporates JSS. It appears that certain CSS properties are causing errors. Specifically, the pointerEvents and ...

The CSS for a VueJS compiled app seems to fail to apply properly unless manually copied and pasted into the browser's style editor

After compiling my vuejs app with npm run build, I noticed that the CSS does not display when viewing it in Firefox. Surprisingly, the styles do load in the network tab and appear under the style editor, but with "0 rules". However, everything displays fin ...

I'm having trouble launching the Vue UI after successfully installing the Vue CLI - any ideas why?

After installing the following versions: node 8.11.2 npm 6.3.0 I proceeded to install the Vue CLI (@vue/[email protected]): npm i -g @vue/cli However, upon running the command below: vue ui An error message was displayed as follows: Error: Cann ...

The request for the option was unsuccessful due to a 404 error

I'm facing an issue with sending a GET request from my frontend to an API application, both running on my local machine. The setup looks like this: backend <===> frontend <=x=> API application Each component runs in its own docker contai ...

TypeScript - create an Interface that must have either the error field or the payload field, but

My Action type has the following requirements: MUST have a field type {String} CAN include a field payload {Object<string, any>} CAN include a field error {Error} Constraints: IF it contains the field payload THEN it cannot contain the field er ...

Is there a method to hide the "Add Image" button from the AssetManager in the GrapesJS editor within a Vue component?

Is there a way to remove the Add Image button and its corresponding textbox? Can this be achieved by adjusting the assetManager configuration or through another method? Upon initializing, the editor can be configured as follows: container: this.fo ...

Troubleshooting NodeJS CORS issue in Vue project as localhost API calls fail

Having an ongoing project that utilizes a NodeJS/Express backend and a VueJS frontend, I am consistently encountering CORS errors: Cross-Origin Request Blocked: The Same Origin Policy restricts access to the external resource at https://localhost:8080/api ...

How can you reposition a component within the dom using Angular?

Just started learning Angular, so I'm hoping this question is simple :) Without getting too specific with code, I could use some guidance to point me in the right direction. I'm currently developing a small shopping list application. The idea i ...

What could be causing the import alias issue in the latest version of Next.js, version 12

Below are my CompileOptions: { "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": false, "skipLibCheck": tr ...

Error Encountered in Vue.js when Trying to Access a Nested

Below is a snippet of my route code from app.js let routes = [{ path: "/dashboard", component: require("./components/Dashboard.vue") }, { path: "/tour", component: require("./components/Index.vue"), children: [{ name: &apos ...

Tips for displaying HTML content dynamically in React using TypeScript after setting a stateVariable

To render an HTML block after successfully setting a state variable, I have defined my state variables and functions below. The code snippet is as follows: const formService = new FormService(); const [appointmentDate, setAppointmentDate] = us ...

What is the best way to make two buttons align next to each other in a stylish and elegant manner

Currently, I am diving into the world of glamorous, a React component styling module. My challenge lies in styling two buttons: Add and Clear. The goal is to have these buttons on the same row with the Clear button positioned on the left and the Add button ...

What is the best approach to implement server-side rendering in Next.js while utilizing Apollo React hooks for fetching data from the backend?

I have a Next.js project that is utilizing Apollo GraphQL to retrieve data from the backend. My goal is to render the page using server-side rendering. However, I am encountering an obstacle as the React hooks provided by GraphQL Apollo prevent me from cal ...

How can I extract a value from an object that is readonly, using a formatted string as the key?

I encountered a situation where I have code resembling the following snippet. It involves an object called errorMessages and multiple fields. Each field corresponds to various error messages in the errorMessages object, but using a formatted string to retr ...

Modify the color of the selected row in the v-data-table

I am trying to customize the background color of the selected row in a v-data-table. <v-data-table dense :headers="headers" :items="records" @click:row="handleClick"> <!-- handleClick is a function that lo ...

The scroll animation feature was not functioning properly in Next.js, however, it was working flawlessly in create react app

I recently transitioned a small project from Create React App (CRA) to Next.js. Everything is working as expected except for the scroll animations in Next.js, which are not functioning properly. There are no errors thrown; the animations simply do not occ ...

JavaScript - Imported function yields varied outcome from module

I have a utility function in my codebase that helps parse URL query parameters, and it is located within my `utils` package. Here is the code snippet for the function: export function urlQueryParamParser(params: URLSearchParams) { const output:any = {}; ...

How to access parent slider variables in an Angular component

I've developed a slider as the parent component with multiple child components. See the demo here: https://stackblitz.com/edit/angular-ivy-gcgxgh?file=src/app/slide2/slide2.component.html Slider in the parent component: <ng-container *ngFor=&quo ...