LoginSignup
4
2

More than 3 years have passed since last update.

Vueのv-modelとBootstrapのradio button groupを一緒に使う.

Last updated at Posted at 2020-01-11

やりたい事

Vueの環境で,Bootstrap Checkbox and radio buttonsを使い,以下のようなトグルボタンを作る.

See the Pen Vue_bootstrap4_checkbox&radio_button by Hirokazu Narui (@hirokazu-narui) on CodePen.

はまった事

Bootstrap Checkbox and radio buttonsに従い,以下のようなコードを書いたところ,Vueのv-modelがリアクティブでなくなった.

html
<div class="btn-group btn-group-toggle mx-2 my-2" data-toggle="buttons">
  <label class="btn btn-outline-secondary">
    <input type="radio" id="white" v-model="color" value="white"> White
  </label>
  <label class="btn btn-outline-secondary">
    <input type="radio" id="black" v-model="color" value="black"> Black
  </label>
  <label class="btn btn-outline-secondary">
    <input type="radio" id="brown" v-model="color" value="brown"> Brown
  </label>
  <label class="btn btn-outline-secondary active">
    <input type="radio" id="none" v-model="color" value="" checked> None
  </label>
</div>

以下のようにトグルボタンの表示は反応しているが,v-modelcolorに値が入らない.


See the Pen
Vue_bootstrap4_checkbox&radio_button_ng
by Hirokazu Narui (@hirokazu-narui)
on CodePen.


原因

Stack OverflowのVue v-model not reactive with BS4 radio button groupの回答のように,VueとBootstrapの両方のJavascriptからトグルボタンの表示をDOM操作しようとしていた.

そのため,Bootstrap側のJavascriptであるdivタグにあるdata-toggle="buttons"を削除し,labelタグに対して:class="{ active: color === 'white' }"のようにVueからactiveクラスにデータバインディングすることで問題を解決.

教訓

あるオブジェクトに対してVueとBootstrapから同時にDOM操作してはいけない.

4
2
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
2