おぴよの気まぐれ日記

おぴよの気まぐれ日記

岡山やプログラミング、ファッションのこと、子育てや人生、生き方についての備忘録。

【Rails】Vue.js入門してみた。(rails new ~ hello?)

Ruby on Rails + Vue.jsで最初の画面「Hello Vue!」が表示されるまでの方法を紹介します。

実行環境

  • Ruby: 2.6.3
  • Rails: 6.0.0
  • yarn: 1.19.1
  • vue: 3.12.0

rails newまで

先ずはrails単体で「Hello World」が表示されるまでです。

$ mkdir vue-app
$ cd vue-app

$ ruby -v
$ rbenv versions
$ rbevn local 2.6.3


# Gemfile作成
$ bundle init

Gemfileを開くとgem "rails"がコメントアウトされているので、コメントアウトを解除する

# gem "rails" <- ここのコメントアウトを外す

bundle installする

$ bundle install --path vendor/bundle

rails newします。

ここで--webpack=vueを設定するとvueの設定がinstall済で構築できます。

が、今回は後々設定する形でやっていこうと思います。

# railsの雛形を作ります
$ bundle exec rails new . -B -d postgresql

# Gemfileが更新されるので再度install
$ bundle install --path vendor/bundle

# DBの作成します
$ bundle exec rake db:create
$ bundle exec rake db:migrate

# サーバー起動します
$ bundle exec rails s

f:id:opiyotan:20191025195746p:plain

どん!

お馴染みの画面が表示されたらokです。

vueを使ってHello World表示させる

先ずは、vueを使えるように設定します。

設定方法は、githubのwebpackerに書かれてます。 https://github.com/rails/webpacker#vue

$ bundle exec rails webpacker:install
$ bundle exec rails webpacker:install:vue

次に表示させるためのコントローラーと画面を作ります。

$ bundle exec rails g controller home index

# routes.rb
Rails.application.routes.draw do
  root 'home#index'
end

# application.html.erb
.
.
  <body>
    <%= yield %>
    <%= javascript_pack_tag 'hello_vue' %> <- これを追加します。
  </body>

これで準備は完了です!

rails sして画面を開くと...

Rails + VueでHello Worldを表示
rails + vueでHello Worldを表示する

「Hello Vue!」が表示されていればokです!

vueファイルをいじってみる

<%= javascript_pack_tag 'hello_vue' %>で読み込んだhello_vueapp/javascript/packs/hello_vue.jsを参照しています。

このファイルの真ん中に使い方が色々と書いてあります。

  • 既存のhtml / erbテンプレートの要素をターゲットにできるようにするには、上記のコードをコメントアウト
  • このマークアップをHTMLテンプレートに追加します。

なので、先ほど作ったhome/index.html.erbhello.vue.jsを変更していきます。

# index.html.erb

<div id='hello'>
  {{message}}
  <app></app>
</div>
# hello.vue.js

import Vue from 'vue/dist/vue.esm'
import App from '../app.vue'

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

ここまで出来たらもっかいrails sで画面を確認してみます。

画面左上に「Can you say hello?」が表示されていればokです。

これは、vueで定義した変数messageの文字列をhtmlで定義した{{ message }}で表示させています。

Vue.jsは絶賛勉強中なので、随時使い方は別の記事でまとめていきたいと思います。

Tips

bundle installでエラーになった場合

$ bundle install --path vendor/bundle
.
.
.
Resolving dependencies...
Bundler could not find compatible versions for gem "sprockets":
  In snapshot (Gemfile.lock):
    sprockets (= 4.0.0)

  In Gemfile:
    sass-rails (~> 5) was resolved to 5.1.0, which depends on
      sprockets (>= 2.8, < 4.0)

    rails (~> 6.0.0) was resolved to 6.0.0, which depends on
      sprockets-rails (>= 2.0.0) was resolved to 3.2.1, which depends on
        sprockets (>= 3.0.0)

Running `bundle update` will rebuild your snapshot from scratch, using only
the gems in your Gemfile, which may resolve the conflict.

エラー文を見ると、 sass-railsのバージョンが引っかかってるのが分かるのでGemfileのバージョン指定されているのを外してあげます。

gem 'sass-rails', '~> 5'

↓

gem 'sass-rails'

rails webpacker:installでエラーになった場合

DEPRECATION WARNING: Single arity template handlers are deprecated. Template handlers must
now accept two parameters, the view object and the source for the view object.
Change:
  >> Coffee::Rails::TemplateHandler.call(template)
To:
  >> Coffee::Rails::TemplateHandler.call(template, source)
 (called from <main> at /Users/tnakano/rails/vue-app/Rakefile:6)
DEPRECATION WARNING: Single arity template handlers are deprecated. Template handlers must
now accept two parameters, the view object and the source for the view object.
Change:
  >> Coffee::Rails::TemplateHandler.call(template)
To:
  >> Coffee::Rails::TemplateHandler.call(template, source)
 (called from <main> at /Users/tnakano/rails/vue-app/Rakefile:6)
RAILS_ENV=development environment is not defined in config/webpacker.yml, falling back to production environment
rails aborted!
Webpacker configuration file not found /Users/tnakano/rails/vue-app/config/webpacker.yml. Please run rails webpacker:install Error: No such file or directory @ rb_sysopen - /Users/tnakano/rails/vue-app/config/webpacker.yml

Please run rails webpacker:install Error: No such file or directoryこの辺りが怪しいですかね。これをそのまま検索してみるとwebpackerがインストールされてないと出るエラーみたいなので、Gemfileに追加します。

# Gemfile
gem 'webpacker', '~> 4.x'

追加したらbundle installします。

また、yarnがインストールされていない場合もエラーになるみたいなのでその場合はbrewを使ってインストールします。

$ brew install yarn