LoginSignup
1
1

More than 3 years have passed since last update.

vueのフォームでenumを使う

Posted at

今作っているアプリでは登録フォームにVueを使っています。
element-uiを使っているのですが、el-selectにenumで定義したものをどうやって持ってくるのかがわからず、試行錯誤を重ねた末なんとかできました!

class Api::V1::InitialisationsController < Api::V1::ApplicationController

  def show
    *省略
    @results = Trade.results.keys
                     *enumで定義したのを呼び出すときは複数形で書くらしい
    respond_to do |format|
      format.json {render :json =>
        {
          *省略
          results:          @results,
        }
      }
    end
  end

end

こういう感じでAPIコントローラーに定義し、

import Vue           from 'vue/dist/vue.esm.js';
import Notifications from 'vue-notification';
import ElementUI     from 'element-ui';
import               'element-ui/lib/theme-chalk/index.css';
import locale        from 'element-ui/lib/locale/lang/ja';
import superagent    from 'superagent';

Vue.use(ElementUI, { locale })
Vue.use(Notifications)
//see https://www.npmjs.com/package/vue-notification

const token = document.getElementsByName('csrf-token')[0].getAttribute('content')

window.onload = function(){
  var trade = new Vue({
    el: "#trade",
    data: {
      results: []
    },
    created: function() {
      superagent
      .get(`/api/v1/initialisations.json`)
      .set('X-CSRF-Token', token)
      .set('Accept', 'application/json')
      .end(function(error, data){
        trade.$data.results = data.body.results
      })
    }
  })
}

こうして

<el-select placeholder="result" v-model="trade.result">
  <el-option
   v-for="result in results"
   :key="result"
   :label="result"
   :value="result"
  >
</el-select>

こういう感じで書くとenumで定義したのが使えます!
登録した時もちゃんと意図したものが保存されました!

よかったよかった。

1
1
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
1
1