vuejs v-model, multiple checkbox and computed property

后端 未结 2 861
栀梦
栀梦 2021-01-13 14:35

I am trying to use multiple checkboxes in single file component. And I need to computed property, but I have boolean newVal instead of array in my setter. Here is my code:

相关标签:
2条回答
  • Here it is the working version:

    var demo = new Vue({
      el: '#demo',
      data: {
        checkedNames: []
      }
    })
    <script src="https://unpkg.com/vue@2.1.10/dist/vue.js"></script>
    <div id="demo">
      <input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
      <label for="jack">Jack</label>
      <input type="checkbox" id="john" value="John" v-model="checkedNames">
      <label for="john">John</label>
      <input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
      <label for="mike">Mike</label>
      <br>
      <span>Checked names: {{ checkedNames }}</span>
    </div>

    if you want to use a computed property you can use it in this way:

    var demo = new Vue({
      el: '#demo',
      data: {
        checkedNames: []
      },
      computed : {
        checkedComputed () {
          return this.checkedNames
        }
      }
    })
    <script src="https://unpkg.com/vue@2.1.10/dist/vue.js"></script>
    <div id="demo">
      <input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
      <label for="jack">Jack</label>
      <input type="checkbox" id="john" value="John" v-model="checkedNames">
      <label for="john">John</label>
      <input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
      <label for="mike">Mike</label>
      <br>
      <span>Checked Names :</span>
      <span>{{ checkedComputed }}</span>
    </div>

    0 讨论(0)
  • 2021-01-13 14:52

    Properties that start with _ or $ will not be proxied on the Vue instance because they may conflict with Vue’s internal properties and API methods. You will have to access them as vm.$data._property.

    From the official documentation.

    0 讨论(0)
提交回复
热议问题