2024-03-10
How to add Vue.js to your Ruby on Rails app with importmaps
Step 1 - Pin Vue to your project
in config/importmap.rb
add the following line
pin "vue", to: "https://ga.jspm.io/npm:vue@3.2.26/dist/vue.esm-browser.js", preload: true
Step 2 - Initialize Vue app
create app/javascript/vue.js
import * as Vue from "vue"
import HelloWorld from "./components/HelloWorld"
document.addEventListener("DOMContentLoaded", () => {
const element = document.querySelector("#app");
if (element !== null) {
const app = Vue.createApp({});
// register your components
app.component('hello-world', HelloWorld);
app.mount("#app");
}
});
Step 3 - Import Vue.js in application.js
in app/javascript/application.js
add the following line
import "./vue"
Step 4 - Create components folder
create app/javascript/components
Then add your Vue component app/javascript/components/HelloWorld.js
const HelloWorld = {
template: `
<div>
<h1></h1>
</div>
`,
data() {
return {
message: 'Hello, Vue!'
};
}
}
export default HelloWorld;
Step 5 - Add to component to view
in home/index.html.erb
<div id="app">
<hello-world></hello-world>
</div>