【问题标题】:Change Event Only fires once in a checkbox input更改事件仅在复选框输入中触发一次
【发布时间】:2020-08-29 16:57:44
【问题描述】:

我有一个复选框组件,我在其中向父组件发出事件。 在父组件中,我想根据复选框是否被选中来做一些事情,但它只触发一次

复选框组件:

<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>

警报仅在复选框状态的第一次更改中显示,我怎样才能使其对所有选中/取消选中做出反应?

我尝试在父组件上使用 v-model,但 v-model 忽略了第一个值(index.checked)并且只依赖于组件数据,我不能将我的数据属性设置为 index.checked,因为它是仅在 v-for 内可用

【问题讨论】:

    标签: javascript forms vue.js dom-events v-model


    【解决方案1】:

    您可以在checkbox-component 上使用v-model,但您需要将value 作为道具传递给子组件以使其具有反应性,然后您可以将checkbox-component 上的checked 属性绑定到该传递prop 值并使用$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>

    【讨论】:

      猜你喜欢
      • 2011-11-03
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      • 1970-01-01
      相关资源
      最近更新 更多