首页 > 解决方案 > 样本生成器,对空值和未定义值停止函数

问题描述

我正在完成一个样本生成器,如果按下发布按钮,我想捕获任何空字段、空值等。它运行打印出样本的发布功能。

有 2 个颜色值和 1 个名称值,如果出现任何警报,我想显示一个警报,并杀死该函数,如在 php 中死,以防止它发布空样本。

这是我到目前为止所得到的,但它有点混乱。

      let value1 = this.value1;
      let value2 = this.value2;
      let name = this.value3;
      if(value1 == undefined && value2 == undefined && name == null) {
        Vue.swal('Please enter a gradient');
      }
      if(name == '') {
        Vue.swal('Please enter a name');
      }

值 1 和 2 是颜色输入,值 3 是输入表单时的名称,然后点击运行它的发布按钮。宁愿抓住它们,只提醒一个通用消息,比如请输入渐变和名称,而不是为每个错误单独提醒。以下是在各种情况下发布的内容。

在空白字段上发布

以下是获取值的函数:

      getName(e) {
      // Get the name value
      if (e.key === "Enter")
      this.$emit('input', {
      value3: +this.value3
      });
      return this.value3;
   },
  // Pick and Set the BG Gradient to main div
    setbgColor() {
    // Get/Set bg and gradient values
      let bg = document.getElementById('bodybg');
      this.$emit('input', {
      value1: +this.$refs.value1.value,
      value2: +this.$refs.value2.value,
      });
      bg.style.background = `linear-gradient(to right, ${this.value1}, 
      ${this.value2})`;

标签: javascriptvue.js

解决方案


使用||代替&&,否则它只会在所有错误都存在时才显示消息。要防止运行剩余的语句,请使用else

publishSwatch() {
  let value1 = this.value1;
  let value2 = this.value2;
  let name = this.value3;
  if (value1 == undefined || value2 == undefined || name == null) {
    Vue.swal('Please Enter Name and Color Values');
  } else {
    this.createSwatch();
    this.resetForm();
    this.handleSwatch();
  }
}

推荐阅读