[Vuejs]-Vuejs computed properties with array

1👍

I would expect the car objects to have something like a color property on them. If this is true, you don’t need computed property, and you can use the following snippet:

<div v-for="car in cars">
   <span :color="car.color"></span>
</div>

However, it seems your code has more problems than just what you described. span is a native HTML element, and as far as I know, it has no color attribute, like your code seems to assume.

Also, your cars data property is an empty array, so looping throught it won’t work very well. You would need something like this to make the previous snippet work (if we forget the span problem):

data() {
   return {
     cars: [
       { color: 'red' },
       { color: 'blue' }
     ]
   }
}

UPDATE:

You don’t need to use a computed property for that, you could rather use a method:

<div v-for="car in cars">
   <span :color="getColor(car)"></span>
</div>
methods: {
  getColor(car) {
    if (car === 'a') {
      return 'black'
    } else if (car === 'b') {
      return 'blue'
    }
  }
}
👤ajobi

1👍

You shouldn’t be using a computed property but a method, since it needs to receive an argument (the car variable, that is). Some tips:

  • Since it’s technically a gets a value, perhaps getColor() will be a more appropriate name
  • Always use === when appropriate
methods: {
  getColor(car) {
    if (car === 'a') {
      return 'black'
    } else if (car === 'b') {
      return 'blue'
    }
  }
}

Then you can use it in the template as such:

<div v-for="car in cars">
   <span :color="getColor(car)"></span>
</div>
👤Terry

1👍

Because you can’t pass param into computed function, you need to get all array of colors or use method instead.

Solution1: Get list of all colors.

<div v-for="(car, index) in cars">
   <span :color="carColors[index]"></span>
</div>
...
computed: {
  carColors() {
    return this.cars.map(car => car === 'a' ? 'black' : 'blue');
  }
}

Solution2: Use method instead as @Terry’ answer.


<div v-for="car in cars">
   <span :color="getColor(car)"></span>
</div>
...
methods: {
  getColor(car) {
    if (car === 'a') {
      return 'black'
    } else if (car === 'b') {
      return 'blue'
    }
  }
}

0👍

You should use a method, not a computed variable since it gets a parameter (car’s id or so)

Create a method named setColor

setColor(car) {
     if (car === 'a') {
        return 'black'
      } else if (car === 'b') {
     return 'blue'
 }
},

Leave a comment