気ままに気ままのエンジニアブログ

定期的に得た知見を気ままに発信中

【Rails/Vue.js】'v-model.number'を定義したら「The input element's type ('number') does not support selection.」エラー発生時の対処方法

こんにちは。

最近布団が離してくれなくて、朝起きれません。

どうもハチマキです。

はじめに

Vue.jsでイベントハンドラ(v-model)を実装中、The input element's type ('number') does not support selection.のエラーが発生しました。
解決に少々苦戦したため、解決方法に関して書いていきたいと思います。

実現したいこと

  • AとBの合計金額を算出する

問題

  • 合計金額を算出する上で、'vue-model.number'をhtmlで定義したら、The input element's type ('number') does not support selection.が発生した

console.logのエラー確認

html

<input type="number" vue-model.number ="A"

ブラウザ
f:id:hachimaki37:20210126114951p:plain

調査

よく記載のあった解決方法は下記のような方法が確認できました。

  • input type="number"を定義する
  • number装飾子を追加する(vue-model.number)
  • JSファイルの対象の値を、parseInt()を指定して値を整数値で返す

これを試しましたが、なかなか解決できず苦戦しました。

解決方法

input typeを'text'に指定し、JS側で各値を整数値(parseInt())で返すことで解決に至りました。
htmlファイル

#total
 = ~~ do |i|
 
   %td= i.input :total, input_html: {type: 'text', 'vue-model' => 'A'}
   %td= i.input :total, input_html: {type: 'text', 'vue-model' => 'B'}

JSファイル(js.coffee)

init = -> 
 new Vue
 el: document.getElementById 'total'
 data:
  A: 0
  B: 0
 computed:
  total: ->
   return parseInt(A) + parseInt(B)  #parseInt(A + B)にするとABと文字列同士が演算されてしまう

これでエラー解決および演算の動作が正常になりました。