railsにvue.jsを入れる

せっかくrailsapiを作ったので、vueを導入して表示できるようにしたいと思いました。

vueを入れる流れを書いておこうと思います。

 

流れ

gemを追加

Gemfileに以下を追記してbundle installします。

gem 'webpacker', github: 'rails/webpacker'

 

 

webpackerをインストール

以下のコマンドを実行してwebpackerをインストールします。

rails webpacker:install

 

※この時以下のようなエラーが出たので、手動でconfig配下にwebpacker.ymlを作成し、もう一度実行し直しました。

RAILS_ENV=development environment is not defined in config/webpacker.yml, falling back to production environment

rails aborted!

Webpacker configuration file not found /Users/hayashiyoshino/projects/rails-projects/api_practice/config/webpacker.yml. Please run rails webpacker:install Error: No such file or directory @ rb_sysopen - /Users/hayashiyoshino/projects/rails-projects/api_practice/config/webpacker.yml

/Users/hayashiyoshino/projects/rails-projects/api_practice/config/environment.rb:5:in `<main>'

/Users/hayashiyoshino/projects/rails-projects/api_practice/bin/rails:9:in `<top (required)>'

/Users/hayashiyoshino/projects/rails-projects/api_practice/bin/spring:15:in `require'

/Users/hayashiyoshino/projects/rails-projects/api_practice/bin/spring:15:in `<top (required)>'

./bin/rails:3:in `load'

./bin/rails:3:in `<main>'

 

Caused by:

Errno::ENOENT: No such file or directory @ rb_sysopen - /Users/hayashiyoshino/projects/rails-projects/api_practice/config/webpacker.yml

/Users/hayashiyoshino/projects/rails-projects/api_practice/config/environment.rb:5:in `<main>'

/Users/hayashiyoshino/projects/rails-projects/api_practice/bin/rails:9:in `<top (required)>'

/Users/hayashiyoshino/projects/rails-projects/api_practice/bin/spring:15:in `require'

/Users/hayashiyoshino/projects/rails-projects/api_practice/bin/spring:15:in `<top (required)>'

./bin/rails:3:in `load'

./bin/rails:3:in `<main>'

Tasks: TOP => app:template => environment

(See full trace by running task with --trace)

 

 

vueをインストール

以下のコマンドを実行してvueをインストールします。

rails webpacker:install:vue

 

 

コントローラ作成

commentsコントローラーを作成します。

rails g controller comments

 

 

ルーティング設定

indexは通常のコントローラ、showアクションは以前作成したapiのコントローラでルーティング設定してあります。

config/routes.rb

Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
namespace 'api' do
namespace 'v1' do
resources :comments, only: [:show]
end
end
resources :comments, only: [:index]
end

 

 

ビュー作成

とりあえずvueをインストールした時に生成されたhello_vue.jsを表示させてみます。

views/comments/index.html.erb

<%= javascript_pack_tag 'hello_vue' %>
<%= stylesheet_pack_tag 'hello_vue' %>

 

localhost:3000/commentsへアクセスするとちゃんと表示されてくれました。

gyazo.com

 

 

感想その他

作成したデータを表示する部分は明日にでもかこうと思います。