programing

vue에서 어레이를 모델로 사용하는 경우 확인란 값을 가져오는 방법

prostudy 2022. 5. 13. 23:49
반응형

vue에서 어레이를 모델로 사용하는 경우 확인란 값을 가져오는 방법

다중 체크박스 목록의 모델로 어레이를 사용하는지 궁금한데, 해당 어레이와 하나씩 비교하기보다 어떤 항목이 체크되고 어떤 항목이 체크되지 않았는지 어떻게 효율적으로 확인할 수 있을까?

<ul>
<li v-for="task in tasks">
<input type="checkbox" :id="task.title" :value="task" v-model="selectedTasks" @change="handleTasks(task)">
<label :for="task.title">{{task.title}}</label>
</li>
</ul>


new Vue({
  data: {
      tasks: [
        { title: 'Go to the store' },
        { title: 'Clean the house' },
        { title: 'Learn Vue.js' }
      ],
      selectedTasks: []
  },
})

각각에 속성을 추가할 수 있음task(예:checked() 각 입력에 바인딩하십시오.v-model, 작업 확인/수정 여부를 확인하는 코드에서 사소한 작업 만들기:

new Vue({
  el: '#app',
  data() {
    return {
      tasks: [
        { title: 'Go to the store', checked: false },
        { title: 'Clean the house', checked: false },
        { title: 'Learn Vue.js', checked: false }
      ]
    };
  },
  methods: {
    clearCheckedTasks() {
      this.tasks = this.tasks.filter(x => !x.checked);
    }
  }
})
<script src="https://unpkg.com/vue@2.5.16"></script>

<div id="app">
  <ul>
    <li v-for="task in tasks">
      <input type="checkbox" :id="task.title" v-model="task.checked">
      <label :for="task.title">{{task.title}}</label>
    </li>
  </ul>
  
  <button @click="clearCheckedTasks">Clear checked tasks</button>
  
  <h3>tasks (live)</h3>
  <pre>{{tasks}}</pre>
</div>

"또한 클릭할 때 한 항목이 체크되었는지 체크되지 않았는지 체크되지 않았는지 알고 싶다"는 당신의 코멘트를 바탕으로 DOM Event 개체를 사용하여 체크되었는지 여부를 탐지할 것이다.

데모: https://jsfiddle.net/jacobgoh101/m480bupd/6/

덧셈을@click="clickHandler"입력을 발휘하여

<input type="checkbox" :id="task.title" :value="task" v-model="selectedTasks" @change="handleTasks(task)" @click="clickHandler">

사용하다e.target.checked을 얻다checked

methods: {
    clickHandler(e) {
        console.log(e.target.checked);
    },
    // ...
  }

루프 인덱스 사용:

<li v-for="(task, index) in tasks">
  <input type="checkbox" :id="task.title" :value="task" v-model="selectedTasks[index]" @change="handleTasks(task)">
  <label :for="task.title">{{task.title}}</label>
</li>

참조URL: https://stackoverflow.com/questions/51433232/how-to-get-checked-value-of-checkbox-if-use-array-as-a-model-in-vue

반응형