vue.js中的多个条件

时间:2018-06-24 22:53:44

标签: javascript if-statement vue.js frontend

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

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

例如

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

这是我的第一个代码:

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

这是我的第二个代码:

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

2 个答案:

答案 0 :(得分:1)

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

例如:

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

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

答案 1 :(得分:1)

我不知道您的代码到底是什么问题,但是您可以使用方法和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()
  }
});