In fact, I could include a link to CDN just like I could with jQuery. There was no need to install transpilers or other system dependencies. Because all I’m looking for is a library to allow me to add some interactive components (e.g. nested forms, wizards, and interactive selections), Vue.js feels like the right tool for the job. For more reasons to choose Vue.js over the alternatives, you may want to check out this post.
Create a new Rails project:
$ rails new vue_example_app --webpack=vue
Or if you have an existing Rails app that has Webpacker installed run:
$ bundle exec rails webpacker:install:vue
This creates an
Once you’ve added that, be sure to start up the webpack dev server with:
For simplicity you may want to consider a tool like Foreman to manage spinning up both the Rails development server and the webpack server with a single command.
# Procfile web: bundle exec rails server -p \$PORT -e \$RACK_ENV webpack: bin/webpack-dev-server
Be sure to explicitly state the RACKENV in a .env file or Rails will complain about not being provided with a secretkey_base. To do this, add the following:
# .env RACK_ENV=development
Hello World from Webpacker
This message is being generated in
Add the following line:
This will append a message of “Hello Vue” to any view you render, but the message will not appear again if you navigate away, while using Turbolinks. We’ll fix this in the next section. To keep things organized, I recommend move
// Original import App from './app.vue'
// Revised import App from '../components/app.vue'
After making this change, you’ll need to restart the webpack dev server.
Depending on your use case, it may or may not make sense to use Vue and Turbolinks together. If you’re building one page application, you want to opt for vue-router instead. For my application, I’m just adding a few Vue components for some added interaction. To make Vue and Turbolinks work side by side, I’m using
vue-turbolinks. To install this package, run the following and then restart your webpack dev server:
$ yarn add vue-turbolinks
Once you’ve installed vue-turbolinks, you need to enable it.
Now, that we have code triggered whenever we navigate using Turbolinks, let’s create a
div to bind our Vue application to. For sake of example, let’s use a DOM element with
At this point, nothing happens even if the necessary
div is present. This is because Vue package default to only including the “runtime-only” build, not the “standalone” build, which is necessary to target elements in existing HTML templates. If you’re interested in learning more about the differences, click here. Fortunately, the fix for this is simple:
// Old import Vue from 'vue'
// New import Vue from 'vue/dist/vue.esm'
Now everything should work as expected. Hope this helps you get up and running.