LoginSignup
3
5

More than 5 years have passed since last update.

Rails + Ajax で Vue.js のバインディングを利用する

Last updated at Posted at 2017-09-06

やりたかったこと

  • JavaScriptやjqueryのDOM操作を利用せずに画面上のテキストを更新させる
  • Vue.jsのバインディングがRailsのAjaxから利用できるか確認する

参考サイト

宣言的レンダリング - Vue.js

準備

sample/indexページを用意する。

$ rails g controller sample index

実装

Config

sample/indexページでPOSTも受けられるようにルーティングを追加する。

config/routes.rb
  get  'sample/index'
  post 'sample/index' # 追記

Controller

リクエストがPOSTならインスタンス変数@nowに現在時刻を格納させる。

app/controllers/sample_controller.rb
class SampleController < ApplicationController
  def index

    if request.request_method == 'POST'
      require "date"
      @now = Time.now.strftime("%H時 %M分 %S秒")
    end

  end
end

View

Vue.jsのバインディングを利用して、JavaScript内で変数app.messageに値が代入されると画面上のテキスト(id=app内の{{message}})が更新されるようにする。

app/views/sample/index.js.erb
<!-- HTML -->

<div id="app">
  <p>{{ message }}</p>
</div>

<%= button_to "時刻を更新" , sample_index_path ,remote: true %>

<!-- JavaScript -->

<script src="https://unpkg.com/vue"></script>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            message: '初期値'
        }
    })
</script>
app/views/sample/index.js.erb
app.message = "いまは <%= @now %>です。";

動作

ボタンをクリックすると変数app.messageにテキストが代入されて画面上のテキストが更新される。

vuejs.gif

3
5
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
3
5