SexyMF
SexyMF

Reputation: 11165

Vue js, detect when a value changed to highlight its text

I have this simple a script that generate random number every few moments, everytime rand is not equals to the one before i want to change its backgound-color. possible? So the random number generates 1,1,3 when it gets to 3 i want to hightlight the background. thanks

https://jsfiddle.net/keseyxgm/1/

new Vue({
  el: '#app',
  data: {
    rand: 0
  },
  mounted : function(){
   var me = this;
    setInterval(function(){
        me.rand = Math.floor(Math.random() * 4) + 1 ;
      me.$forceUpdate();
    },1000)
  }
})


<div id="app">
  <p>{{rand}}</p>
</div>

Upvotes: 2

Views: 1669

Answers (2)

omarjebari
omarjebari

Reputation: 5499

A nice approach is to use a watcher with a class binding. See this js fiddle: https://jsfiddle.net/omarjebari/wjf8qbt0/18/

<div id="app">
   <div class="random-element" v-bind:class="{ active: isChanged }">{{ rand }}</div>
</div>
<script>

    new Vue({
        el: "#app",
        data: {
            rand: 0,
            isChanged: false,
        },
        mounted : function(){
            setInterval(() => {
                this.rand = Math.floor(Math.random() * 4) + 1;
            }, 1000);
        },
        watch: {
            rand(newVal, oldVal) {
                console.log(`${newVal} vs ${oldVal}`);
                if (newVal !== oldVal) {
                    this.isChanged = true;
                    setTimeout(() => {
                        this.isChanged = false;
                    }, 300);
                }
            }
        },
    })
</script>
<style>
    div.random-element {
        height: 30px;
        color: black;
        padding: 5px;
    }

    div.active {
        background-color: red;
    }
</style>

Upvotes: 0

thanksd
thanksd

Reputation: 55644

Make a data property to store whether the updated value is different from the current value and bind the background-color to that:

new Vue({
  el: '#app',
  data() {
    return { 
      rand: 0,
      diff: false
    }
  },
  mounted() {
    setInterval(() => {
      let rand = Math.floor(Math.random() * 4) + 1 ;
      this.diff = rand !== this.rand;
      this.rand = rand;
    }, 1000);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="app">
  <p :style="{ 'background-color': (diff) ? 'gold' : 'initial' }">{{rand}}</p>
</div>

Upvotes: 3

Related Questions