LoginSignup
4
3

More than 5 years have passed since last update.

railsでvueをwebpack無しで使う。

Last updated at Posted at 2017-12-14

全面的にSPAにするのでは無くて、部分的にvueの恩威を受けたい時に。

事前準備

gem 'vuejs-rails'

#ES6で書く場合、必要
gem "sprockets"
gem "sprockets-es6"
application.js
//= require vue

画面追加

routes.rb
get 'hoge/:id' => 'moge#hoge'
app/controllers/moge_controller.rb
class MogeController
  def hoge

    # html表示とjson返却を同じアクションにしてみる。
    # format htmlはテンプレート / jsonはデータ
    respond_to do |format|
      format.html { render :hoge }
      format.json { render json: Hoge.find(params[:id]) }
      end
    end
  end
end
assets/javascripts/moge_hoge.es6
//vueコントローラ
function vue_hoge_moge(id){
    new Vue({
        el: '#moge_hoge_app',
        data: {
          hoge:null
        },
        created(){
            $.get(`/hoge/${id}`).then(data=>this.hoge = data)
        },
    });
}
app/views/moge/hoge.haml
#moge_hoge_app
  %p {{hoge.name}}
:javascript
  vue_hoge_moge(#{params[:id]})
4
3
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
4
3