margherita pizza
margherita pizza

Reputation: 7145

VueJS to dynamically control the CSS

enter image description here

My use case is something like this,

  1. I got the star rank from the back-end as a digit(1,2,3,4,5).
  2. If it's number 3 I want to color first 3 stars in yellow and reaming to default color. How do I achieve this using Vue JS?

This is my code.

<template>
  <div id="app">
    <span class="demo">&#9733;&#9733;&#9733;&#9733;&#9733;</span>
  </div>
</template>

<script>

export default {
  name: 'app',
  data () {
    return {

    }
  },
  methods:{

  }
}
</script>

<style>
.demo{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  font-size: 6em;
  color:yellow;
  text-shadow: 0 0 15px blue;
}
</style>

Upvotes: 2

Views: 327

Answers (1)

acdcjunior
acdcjunior

Reputation: 135742

You could use v-for and some CSS classes, as shown below.

They would iterate starRank times creating filled-star stars and then iterate 5 - starRank times creating not-filled-star stars.

In the example below, starRank is 3 and, as such, three stars will be yellow.

new Vue({
  el: '#app',
  data() {
    return {
      starRank: 3
    }
  }
})
.demo {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 6em;
  text-shadow: 0 0 15px blue;
}

.filled-star { color: yellow; }
.not-filled-star { color: blue; }
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <span class="demo">
      <span v-for="index in starRank" class="filled-star">&#9733;</span><span v-for="index in (5-starRank)" class="not-filled-star">&#9733;</span>
  </span>
</div>

Upvotes: 2

Related Questions