VueJS - How to make models and collections? VueJS - How to make models and collections? vue.js vue.js

VueJS - How to make models and collections?


Vue was initially created to bind data to a template in a reactive way, therefore, there's no "controller" or "model" notion like you would have in a regular MVC.

Vue just needs plain javascript objects as data, so if some of your data needs to be mapped to a model, well it's not about Vue, it's about... Javascript.

Here is an example of implementation (in ES6) :

class UserModel {  constructor(data) {    this.data = data  }  name() {    return this.data.firstname + ' ' + this.data.lastname  }  // and so on, put other methods here}var app = new Vue({  el: '#app',  data: {    user: {}  },  created() {    // axios or anything else for your ajax, or a new fetch api    axios.get('/me')      .then(response => {        // of course the "this" here is the Vue instance because i used an es6 arrow function        this.user = new UserModel(response.data)      })  }})

That's it.

As you can see, Vue doesn't have to do with the Model class I created, I just mapped my ajax data to a custom class, then mapped the result to the Vue instance.

As simple as that.