Vue.js チェックボックスの状態を取得する

Vue.js チェックボックスの状態を取得する

Vue.jsで、チェックボックスの状態を取得するサンプルコードを記述してます。 「vue3」を使用してます。

環境

  • OS windows10 pro 64bit
  • Vue.js 3.0.0
  • Apache 2.4.43
  • ブラウザ chrome 92.0.4515.107

チェックボックスの状態を取得

チェックボックスの状態を取得するには、「@click」を使用します。

<input type="checkbox" @click="イベント名">

以下は、チェックボックスにチェックの状態により、テキストの表示・非表示を切り替えるサンプルコードとなります。

※「vue3」は「cdn版」、デザインは「semantic-ui」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- semantic.css  -->
  <link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
  <script src="https://unpkg.com/vue@next"></script>

</head>
<style>
  body>.grid {
    height: 100%;
  }
  .fields {
    margin-top: 5px;
  }
</style>

<body>
  <div id="app" class="ui middle aligned center aligned grid">

    <div class="column">

      <h2 v-show="flg">flg</h2>

      <div class="ui slider checkbox">
        <input type="checkbox" @click="change" tabindex="0" checked>
        <label>checkbox</label>
      </div>

    </div>

  </div>
  <script>

    const hoge = {
      data() {
        return {
          flg: true
        }
      },
      methods: {
        change: function(e) {
          this.flg = e.target.checked
        }
      }
    }

    Vue.createApp(hoge).mount('#app')

  </script>
</body>

</html>

切り替えされていることが確認できます。