How to make rails work with vue.js?
For Rails 5.1+, it will come with yarn & webpack support.
Also, with this pull request to webpacker, Vue will be supported out of the box.
To get started with Vue on Rails,
- Add
gem 'webpacker'
to gemfile bundle install
- Run
rails webpacker:install && rails webpacker:install:vue
Alternatively with Rails 5.1x, do rails new app --webpack=vue
You will be ready for Vue on Rails 5
I managed to make this work with Vue.js.
first I added an el
propertie to the object passed to Vue constructor, and I started to get an error saying that body
element was not defined. Obviously the body element is always present in an html file, so I though it was a problem about when the Vue instances were created. So I simply wrapped all on a ready
event.
$(document).on('ready page:change', function() { var Vue = require('vue'); Vue.use(require('vue-resource')); new Vue({ el: 'body', data: { users: [] }, ready: function(){ this.$http.get('users.json').then(function(response){ console.log(JSON.stringify(response.data)); this.users = response.data; }, function(response){ console.log("fail"); console.log(JSON.stringify(response)); }); } }); });
And that works fine!
Because I'm using turbolinks, I also included the page:change
event. And in my view index.html.erb
I have access to Vue instance. So this make this case working and it's fine for this particular question, however I now have another issue working with .vue
components, maybe I'll open another question about it.
Notice that in my index.html.erb
view I have access to the Vue instance defined in users.js
file in the assets/javascript/
folder, but that I have not access to Vue or any of the js modules loaded with browserify from the views folder
Try using the Breakfast Gem. There is an installation section for Vue.js
Basically once you install the gem you can use npm
to install Vue
, Vuex
and the Vue Router
quite easily.
And it supports single file Vue components.