這邊講一下利用 vue.js 來計算 checkbox 選取的數量的方法。

HTML 的部分:

<div id="app">
  <label for=""><input type="checkbox" v-model="chk" value="1"> 1</label>
  <label for=""><input type="checkbox" v-model="chk" value="2"> 2</label>
  <label for=""><input type="checkbox" v-model="chk" value="3"> 3</label>
  <div>{{chkLength}}</div>
</div>

Vue 的部分:

const App = {
  data() {
    return {
      chk: []
    }
  },
  computed: {
    chkLength: function(){
      return this.chk.length;
    }
  }
}

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

簡單講就是利用 computed 回傳 checkbox 被勾選的數量就好了。

完整程式碼: