Reputation: 1518
I'm a newbie to vuejs and i'm from angular background. I'm trying to bind my setter/getter in v-model for an input. But that is not working as I'm intending it to. But when I tried to bind it to variable directly, then it's working fine.
Following is my code:
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);
}
}
<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>
I was expecting username and password value typed into the respective fields to be displayed in the console. But instead all I get is undefined undefined
(Even though I have initialized the variable to empty string). I did go through the documentation, but it was not of much help since i'm using typescript with vue-class-component. Can anyone please point me in the right direction.
Upvotes: 10
Views: 5616
Reputation: 953
Properties that start with _ or $ will not be proxied on the Vue instance because they may conflict with Vue’s internal properties and API methods. You will have to access them as vm.$data._property.
Simply don't use the _ prefix to solve the problem.
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);
}
}
Upvotes: 12