16

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

zardon
  • 1,601
  • 4
  • 23
  • 46
  • An array of objects? – Bert May 07 '17 at 20:23
  • The array of objects part I understand, but what I'm really after is how do I make the Employee model. I'm finding it hard to find an example where it has a model laid out in code like with name, age, etc. Most examples I've found import their data from a JSON/XML feed when I want to have a fixed list of variables for each Employee instance – zardon May 08 '17 at 00:08
  • I'm not sure I understand. Make an object and add the properties you want to it. You can do that any number of ways.You can use a factory function. Or a class. Or just inline it. – Bert May 08 '17 at 02:20
  • I would like to know what it looks like. In backbone you can make a model like this: `var MyModel = Backbone.Model.extend({})` But I don't know the equivelent in VueJS – zardon May 08 '17 at 07:33
  • Vue uses plain javascript objects for data. It doesn't require any base values. If you want to make an Employee object from an existing Employee object template, use any of the methods I mentioned above, or `Object.assign({}, EmployeeTemplate)`. – Bert May 08 '17 at 15:12
  • Okay, many thanks. I will investigate further. Thanks – zardon May 08 '17 at 16:37

1 Answers1

26

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.

Rachael
  • 1,965
  • 4
  • 29
  • 55
darkylmnx
  • 1,891
  • 4
  • 22
  • 36
  • 1
    There's a typo above: it should be 'constructor' not 'construct' :-) Spend more time than I care to admit before I saw that – Joris Feb 12 '21 at 10:06