10
9

More than 5 years have passed since last update.

BootstrapVueをRailsに導入してみる

Last updated at Posted at 2019-07-10

初投稿です

RailsでBootstrapとVue.jsを使う方法を調べると、
Vue.jsをrails new project --webpack=vueで入れてきて、
BootstrapはGemfileにgem 'bootstrap'を書いてbundle installしてjsやscssをいじって、、、
というのがオーソドックスなやり方のよう

ちょっと面倒なのと、なぜかvueファイルのtemplateに書いたtooltipがちゃんと効いてくれなかったので、Bootstrapをgemで入れないようにして、yarnでBootstrapVueを入れるようにしてみた

BootstrapVue

おなじみBootstrapとVue.jsが合体したもの
公式サイト

やったこと

プロジェクト作成(webpackでvueもインストール)

$ rails new bootstrapvue_rails --webpack=vue

yarnでBootstrapVueをインストール

$ cd bootstrapvue_rails
$ yarn add bootstrap-vue

画面を用意して、ルーティングしてあげる

$ rails g controller Home index
config/routes.rb
Rails.application.routes.draw do
  root to: 'home#index'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

画面のjsファイルを作る

app/javascript/packs/home.js
import Vue from 'vue/dist/vue.esm'
import BootstrapVue from 'bootstrap-vue'
import App from '../app.vue'

import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'

Vue.use(BootstrapVue)

document.addEventListener('DOMContentLoaded', () => {
  const app = new Vue({
    el: '#hello',
     data: {
      message: "Can you say hello?"
    },
    components: { App }
  })
})

vueファイルを作る

app/javascript/app.vue
<template>
  <div id="app">
    <p>{{ message }}</p>
    <div class="text-center my-3">
      <b-button v-b-tooltip.hover title="Tooltip content">Hover Me</b-button>
    </div>
  </div>
</template>

<script>
export default {
  data: function () {
    return {
      message: "Hello Vue!"
    }
  }
}
</script>

<style scoped>
p {
  font-size: 2em;
  text-align: center;
}
</style>

viewで読み込む

app/views/home/index.html.erb
<h1>Home#index</h1>
<p>Find me in app/views/home/index.html.erb</p>

<div id='hello'>
  {{message}}
  <app></app>
</div>

<%= javascript_pack_tag 'home' %>

サーバーを立ち上げたらtooltipが効いてくれてる

$ ./bin/webpack-dev-server
$ rails s

スクリーンショット 2019-07-10 21.05.55.png

10
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9