Integrate Vuejs with Rails

Tram Ho


Vuejs is a javascript framework used to build user interfaces. Vuejs easily meets the needs of building a Single Page Applications with high complexity. Vuejs is widely used with the php community, specifically the laravel framework, but in this article I will introduce you to a new combination that is Vuejs with Ruby On Rails.

So how to combine vuejs and rails, here I would like to introduce a support gem for integrating these two frameworks that is gem Webpacker .

What is webpacker?

Webpacker is a ruby ​​gem used to integrate Webpack into Rails for use with Asset Pipeline. Webpack is simply a tool to encapsulate all js and css files (scss, sass ..). The webpack encapsulation is encapsulated according to the structure of the project, from module to module. With pre-complie coded Js in Rails, this gem is like an angel of salvation in integrating front-end frameworks like ReacJS, VueJS or AngularJS into Rails.



To create a project with Rails and Vuejs, you simply need to use the command

However, if you want to integrate VueJS with an existing project, you can also do the following:
Install gem:

and run

If the installation is successful, you will see a small message asking

There is a little difference between a normal Rails project and a Rails + VueJS project. Have you noticed in the app/javascript will appear the following directory structure

Now that the installation is temporary, try rails s to see if anything happens

Nothing’s changed right, don’t hurry, share or start right now.
First we create a view immediately

Then go to config/routes.rb

OK so the default page has been set

Now go to app/views/static_pages.erb delete everything instead of the following code

Reload the server one more time!

Ok so we have successfully loaded VueJS, if you want to change the default printed text of VueJS when creating the project, you just need to go to app/javascript/app.vue to change


Demo of summing two simple numbers using VueJS

You go to javascript/app.vue and replace the old code content with the new code as follows

Refresh the page and enjoy it. Result:


Share the news now

Source : Viblo