簡體   English   中英

更改事件僅在復選框輸入中觸發一次

[英]Change Event Only fires once in a checkbox input

我有一個復選框組件,我在其中向父組件發送事件。 在父組件中,我想根據復選框是否被選中來做一些事情,但它只觸發一次

復選框組件:

<template>
  <input
     type="checkbox"
     :checked="ischecked"
     @change="$emit('input', !ischecked)"
   />
    </template>

<script>
    props: {
      checked:{
         type: Boolean,
         default: false
      }
    },
    computed: {
        ischecked(){
          // Some checks with the checked prop, will return true or false
        }
    }
</script>

父組件

<template>
 <checkbox-component
     v-for="index in arrayOfData"
     :checked="index.checked"
     @input="test"
  />
</template>

<script>
   (...)
   methods: {
     test:{
       alert('change')
     }
   }
</script>

警報僅顯示在復選框的 state 的第一次更改中,我怎樣才能使其對所有選中/取消選中做出反應?

我嘗試在父組件上使用 v-model 但 v-model 忽略第一個值(index.checked)並且只依賴於組件數據,我不能將我的數據屬性設置為 index.checked 因為它只在內部可用v-for

您可以在checkbox-component上使用v-model但您需要將value作為道具傳遞給子組件以使其具有反應性,然后您可以將checkbox-component上的checked屬性綁定到該傳遞道具值並簡單地發出當前元素使用$event.target.checked檢查狀態,例如:

 Vue.component('checkbox-component', { template: `<input type="checkbox":checked="value" @change="$emit(\'input\', $event.target.checked)" />`, props: ['value'] }) new Vue({ el: "#myApp", data: { arrayOfData: [{ id: 1, checked: true }, { id: 1, checked: false }] }, methods: { test() { console.log('change') } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"> <div id="myApp"> <div v-for="index in arrayOfData"> <checkbox-component v-model="index.checked" @input="test"></checkbox-component> <label> {{ index.checked }}</label> </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM