首页 > 解决方案 > 修改vue js中的复选框行为

问题描述

我有这个复选框

<div class="form-check form-check-inline col-lg-2">
  <input v-model="propertyData.fitness_centre" type="checkbox" class="form-check-input" id="dc_li_u" />
  <label class="form-check-label" for="dc_li_u">Fitness Centre</label>
</div>

我将状态保存在数据库中,因此在编辑状态时会恢复并显示复选框是否被选中。

但是,我需要复选框有一个字符串值,当单击复选框时将其保存到数据库中,这样当复选框具有字符串值时,它会被选中,而当字符串值为空时,复选框不会被选中。

我有很多复选框,所以我希望整个逻辑都包含在复选框中。我如何修改复选框来做到这一点?

标签: vue.jsvuejs2

解决方案


您可以使用change-event 处理程序propertyData.fitness_centre根据检查状态设置为所需的值。还绑定<input>.checked到,propertyData.fitness_centre以便检查状态绑定到模型的真实性(空字符串为false,否则为true)。

<template>
  <input type="checkbox"
         @change="onChange"
         :checked="propertyData.fitness_centre"
         value="fitness_centre">
</template>

<script>
export default {
  data() {
    return {
      propertyData: { fitness_centre: '' }
    }
  },
  methods: {
    onChange(e) {
      this.propertyData.fitness_centre = e.target.checked ? e.target.value : ''
    }
  }
}
</script>

演示


推荐阅读