Penalse
Penalse

Reputation: 185

Multiple conditions in vue.js

I'm new in vue.js and I'm trying to add multiple conditions.

EDIT: First code example works. (I was very tired last night and dunno what I was thinking).

e.g.

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

Here is my first code:

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

Here is my second code:

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

Upvotes: 1

Views: 931

Answers (2)

boudlal
boudlal

Reputation: 82

I don't know what exactly the problem in your code , but you can do the same thing with methods and Lifecycle Hooks instead of computed properties:

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()
  }
});

Upvotes: 1

Mark
Mark

Reputation: 92461

In your second example you are redefining getHoursCondition in the computed function getHoursCondition. That's going to cause a problem of a name clash. You should just return the value you want from the function.

For example:

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

Here's a working fiddle (it says 'good afternoon' to me, which is correct for my time): http://jsfiddle.net/9e53pm2q/

Upvotes: 1

Related Questions