Skip to content

Instantly share code, notes, and snippets.

@jschee
Last active March 12, 2024 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jschee/c81aea565bcc1b75a92823b99cec7a7d to your computer and use it in GitHub Desktop.
Save jschee/c81aea565bcc1b75a92823b99cec7a7d to your computer and use it in GitHub Desktop.
How to add Vue.js in your Ruby on Rails project with importmaps

Step 1 - Pin vue to your project

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>{{ message }}</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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment