Blog Details

Integrating Vue JS with Ruby on Rails application

Vue JS Integration with Rails using Webpacker

Vue is a progressive framework for building user interface.

In this article we are going to integrate Vue JS in our Ruby on Rails application.

rails new rails_vue_demo --skip-turbolinks --webpack=vue

If you noticed, we have passed vue as webpack option. This configuration option is provided by webpacker gem. There are many opther options available. You can find there here

If you have never installed yarn then please install it from here

Now, install Webpacker to your Rails application with following command.

rails webpacker:install

You can also manually add Vue to Rails if your Rails application is already exists.

rails webpacker:install:vue

Now let’s create a controller Home.

rails g controller Home

The above command will generate some controller, tests, JavaScript and CSS files.

Now we have to add root path in routes.rb file

root "home#index"

We will keep our JavaScript files to app/javascripts/packs folder.

Let’s create our first Vue file to create an instance of Vue.

import Vue from 'vue/dist/vue.esm'

document.addEventListener('DOMContentLoaded', () => {
  var app = new Vue({
    el: '#app',
    data: {
      message: 'Hello Vue!'
    },
    methods: {}
  });

  var app3 = new Vue({
    el: '#app-3',
    data: {
      seen: true
    }
  })
});

Here el is used to declare the selector. data used for adding data required by the Vue instance.

Now we have to create our ERB file having div with same selector element. Here I have added some content with sample usage of Vue.

<h1>Rails & Vue.js App</h1>
<div id="app">
  {{message}}
</div>
<div id="app-3">
  <span v-if="seen">Now you see me</span>
</div>

Also, we have to add this vueapp.js file to application.html.erb layout manifest file.

<%= javascript_pack_tag 'vueapp' %>

That’s it!! Restart the server and open localhost:3000 in your browser. You will find the expected results.

Also notice the public/packs/js directory where all the compiled and imported JavaScript files are stored.

When you will load the application for the first time, at that time it will take some time as webpacker is compiling the source. So don’t worry about the performance at that time.

There are different browser extensions provided by Vue community which you can use to inspect your Vue components.

Hope you get some idea of using Vue JS in our Ruby on Rails application.

I will keep sharing more useful content. Keep following and Have a happy coding!