Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS - How to make models and collections?

I am attempting to learn VueJS and I'm finding it hard to understand how to make models and collections.

For example, I want to have a collection (or list) of Employees and each Employee is a model.

But I'm not sure how to accomplish this in VueJS

Many thanks

like image 496
zardon Avatar asked May 07 '17 17:05

zardon


1 Answers

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.

like image 127
darkylmnx Avatar answered Oct 06 '22 15:10

darkylmnx