0

I have some JSON objects passed from an API server like: {"id": 4, "name": "foo", "bar": {"key1": "value1", "key2": "value2"}}

I want to wrap this object with a Javascript class so I can handle the JSON change easily (It's under development and change from time to time). It's a very basic OOP: Wrap the data, then use setters and getters:

export default class Issue {
  constructor(json) {
    this.data = json
  }
  getId() {
    return this.data.id
  }
  isOpen() {
    return this.data.status.id !== 6
  }
  ...
}

But in Vue.js I don't know how to do this while keeping it reactively. For example, in a component I have

data: () => {
  return {
    issues: []
  }
}

Then for (const json of jsons) { this.issues.push(json) } will be reactive, but for (const json of jsons) { this.issues.push(new Issue(json)) } will be not, right?

I think my ideal is that I can use Component as a data class, but I don't know how to new a component, and is it effective to use Components as data classes.

What should I do?

Romulus Urakagi Ts'ai
  • 3,699
  • 10
  • 42
  • 68
  • Did you mean `.push()` instead of `.append()`? Your `issues` array will be reactive provided you use appropriate `key` props, eg `v-for="issue in issues" :key="issue.getId()"`. If the data inside each `Issue` is meant to change though, then I don't think that would work – Phil May 03 '21 at 08:20
  • 1
    I think that data `classes` are more popular in the Angular world - in Vue world data `objects` seem to be the preferred way. – IVO GELOV May 03 '21 at 08:23
  • Oh yeah `.push()`. Was writing python. Maybe I can do with class-like objects. – Romulus Urakagi Ts'ai May 03 '21 at 09:49

0 Answers0