首页 > 解决方案 > VueJS 根据其他按钮情况开/关或隐藏/显示切换按钮

问题描述

我有一张表格,其中包括一周中的几天以及每天、工作日和周末选项。每行有 2 个select项目来选择更新的开始时间和结束时间。在每一行的末尾都有一个切换按钮,用于启用和禁用该特定日期。用户可以单独选择每一天,也可以选择每天选项。当他们启用切换时,禁用的选择元素将被启用,因此他们可以选择特定日期的时间。

这是它的外观; 在此处输入图像描述

如上图,用户可以同时选择 Weekdays 和 Weekend,这应该等于 Everyday 吧?所以我想要做的是当他们一起启用工作日和周末时,应该启用每天切换,而另外两个再次禁用。

这是我的数据和我的方法;

data() {
        return {
        everydayCheck: false,
        weekdaysCheck: false,
        weekendCheck: false,
        customCheck: false,
        mondayCheck: false,
        tuesdayCheck: false,
        wednesdayCheck: false,
        thursdayCheck: false,
        fridayCheck: false,
        saturdayCheck: false,
        sundayCheck: false,
        }
    },

methods: {
       isDisabled: function(){
         if(this.everydayCheck){   return !this.everydayCheck;   }
         else if(this.weekdaysCheck){   return !this.weekdaysCheck;   }
         else if(this.weekendCheck){   return !this.weekendCheck; }
         else if(this.customCheck){   return !this.customCheck;   }
         else if(this.mondayCheck){   return !this.mondayCheck;   }
         else if(this.tuesdayCheck){   return !this.tuesdayCheck;   }
         else if(this.wednesdayCheck){   return !this.wednesdayCheck;   }
         else if(this.thursdayCheck){   return !this.thursdayCheck;   }
         else if(this.fridayCheck){   return !this.fridayCheck;   }
         else if(this.saturdayCheck){   return !this.saturdayCheck;   }
         else if(this.weekdaysCheck && this.weekendCheck){
             return this.everydayCheck, !this.weekdaysCheck, !this.weekendCheck;
         }
         else {  return !this.sundayCheck;   }
      },
   },

else 前面的最后一个else if说如果weekendCheck 和weekdaysCheck 为真,则将everydayCheck 变为true 并使其他为假,还是我错了?它不起作用。我错过了什么?

标签: cssvue.jstoggleshow-hide

解决方案


else if(this.weekdaysCheck && this.weekendCheck){
             return this.everydayCheck, !this.weekdaysCheck, !this.weekendCheck;
         }

这是错误的,因为您要返回 3 个不同的东西,而这在 js 中不受支持。

微不足道,你可以这样做:

else if(this.weekdaysCheck && this.weekendCheck){
   changeWeek();
   return
}

并添加这样的方法:

changeWeek: function(){
  this.everydayCheck=!this.everydayCheck,
  this.weekdaysCheck=!this.weekdaysCheck,
  this.weekendCheck=!this.weekendCheck;
}

但这不是很好的代码。我的建议是尝试使用 v-for 语句生成输入,从这样的对象开始:

data(){
 return{
  inputs: [
   {
    id:everydaycheck,
    active:false,
    ...
   },
   ...
  ]
 }
}

那么你可以制作一个动态的函数:

<template v-for="input in inputs">
  <input @click="isDisabled($event) v-model="input.active" :key="input.id" 
  id="input.id">
</template>

并在您的功能中:

methods:
 isDisabled(event) {
  let id=event.target.getAttribute('id')
  inputs.forEach((input)=>{
  if(input.id == id) {
   input.active=!input.active
  }
  })

 }

推荐阅读