【问题标题】:Multiple conditions in vue.jsvue.js 中的多个条件
【发布时间】:2018-12-03 12:07:38
【问题描述】:

我是 vue.js 的新手,我正在尝试添加多个条件。

编辑:第一个代码示例有效。 (昨晚我很累,不知道我在想什么)。

例如

if hours > 11 && hours < 18 show some text etc..

这是我的第一个代码:

https://jsfiddle.net/hyL723fb/20/

这是我的第二个代码:

http://jsfiddle.net/trcyn2qh/28/

【问题讨论】:

  • 你的第一个例子对我有用。唯一令人困惑的事情可能是您的 if else 没有涵盖 1、11、17 和 24 小时,因为您正在使用 > 而不是 >=
  • 是的,我只是忘记了>=。谢谢!

标签: javascript if-statement vue.js frontend


【解决方案1】:

在第二个示例中,您在计算函数 getHoursCondition 中重新定义 getHoursCondition。这将导致名称冲突的问题。你应该从函数中返回你想要的值。

例如:

if (this.hours > 01 && this.hours < 11) {
        return 'Good morning'; // <-- return the value
    } 

这是一个工作小提琴(它对我说“下午好”,这对我来说是正确的):http://jsfiddle.net/9e53pm2q/

【讨论】:

    【解决方案2】:

    我不知道你的代码到底有什么问题,但是你可以用方法和Lifecycle Hooks 而不是计算属性来做同样的事情:

    new Vue({
      el: '#app',
     data: {
            hours: new Date().getHours(),
        getHoursCondition: '' //define the variable first
      },
      methods: {
         getHours: function () {
        if (this.hours > 01 && this.hours < 11) {
            this.getHoursCondition = 'Good morning';
        } 
        else if (this.hours > 11 && this.hours < 17) {
                this.getHoursCondition = 'Good afternoon';
    }
    else if (this.hours > 18 && this.hours < 24) {
                this.getHoursCondition = 'Good evening';
    } else {
            this.getHoursCondition = 'something';
    }
      }
    },
      mounted(){
         //when the instance is mounted call the method getHours()
          this.getHours()
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      • 2018-05-31
      • 2016-11-24
      相关资源
      最近更新 更多