[Vuejs]-Use Rails 5.1 API with VueJS2

0👍

It’s really quite simple, though unfortunately not documented:

  1. Get rid of webpacker (unnecessary headache, see below)
  2. Use vue from the cdn. It’s cached and you have no work with it.
  3. move your js code into the template
  4. Render your data into the template
    5 (optional) update the data from the json endpoint if (and only if) it changes

To demonstrate, this would be the code in your template (I use haml, it has a :javascript filter)

:javascript
   var v = new Vue({
       el: '#roastslist',
     data: {
       roasts: "#{@rosts.to_json}"
     }

The to_json renders the roasts (as json) and thus makes them available to Vue. to_json has many options (like :only) but if that is not enough, i use rabl.

If (and when) your js code get’s too much, you can move some into different files, or (functions) into the asset pipeline.

PS: I use ruby2js, which reduces the code size by about half (while being easy on the eye)
Also, watch my blog, i’m about to write more on the subject.

0👍

Instead of using Vue’s mounted, try JSON.parse as your data like so:

 var element = document.getElementById('roastslist')
  if (element != null) {
    const v = new Vue({
      el: element,
      data: {
        roastslist: JSON.parse(element.dataset.rosts)
      },
      template: "<roast-list :original_roasts='roastslist' />"
    })
  }
})

Then, in your roasts.js use:

 <tr v-for="roast in original_roasts">
    <td>{{roast.name}}</td>
    <td>{{roast.roaster}}</td>
  </tr>

I changed roasts to original_roasts to signify the passed json object. Also, original_roasts could be passed as a prop array in other components using the same json data.

Leave a comment