Answer the question
In order to leave comments, you need to log in
Reactive class attributes?
There is a certain component in which I receive data from the api and display them.
The code is something like this:
<template>
<div v-if="user">
<input v-model="user.name" />
</div>
</template>
<script>
export default {
data: () => ({
user: null
}),
methods: {
loadUser () {
this.$api.users.show(userId) {
//from response get user instance...
this.user = response
}
}
}
}
</script>
export default class User {
constructor (payload) {
this._original = payload
this._attributes = User.refactorPayload(payload)
this._changed = {}
}
user.getAttribute('name')
getAttribute(key){
if (this._attributes.hasOwnProperty(key)) {
return this._attributes[key]
}
return null
}
Answer the question
In order to leave comments, you need to log in
The option "on the forehead" - do not use "sugar" in the form of v-model, but use
In general, why such a strange organization of the model class? Why didn't you explicitly delimit the User properties? There would be both visibility and addition of the code from IDE.
The second option, if you really really want to pervert with a similar implementation of the model, use the getter / setter mechanism of the language itself :
// age будет высчитывать возраст по birthday
Object.defineProperty(this, "age", {
get: function() {
var today = new Date();
var yearDelta = today.getFullYear() - this.birthday.getFullYear();
if (today.getMonth() > this.birthday.getMonth() ||
(today.getMonth() === this.birthday.getMonth() && today.getDate() >= this.birthday.getDate())) {
return yearDelta;
}
return yearDelta - 1;
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question