Changing Img Src with Vue JS

Hi there , I was learning vue js now and i was playing around with hover effect.
I tried to change the Src attribute of image when mouse was hovered.
the HTML tag was like this :-1:


<img @mouseover="hover=true"
    @mouseleave="hover=false"
     :src="btn_img"
    class="button">

And the Vue js was like this:

var vm=new Vue({
  el:'.top_container',
  data:{hover:false,
btn_img:"https://i.imgur.com/2RJTr2f.png"
       },
  methods:{
    btn_changer :function(){
      if (hover){
       
        btn_img="https://i.imgur.com/ApvguGb.png"
      }
      else{
        btn_img="https://i.imgur.com/2RJTr2f.png"
      }
    }
  }
})

What exactly am i missing here , the full code can be found in https://codepen.io/mgcsandip/pen/PoNLGWy

  1. You should use watch to watch for hover changes.

  2. btn_img is missing this (all props from data are accessible with this).

P.S. It’s better to get used to write data as function (doesn’t matter in this case, but when working with components it’s required).

1 Like

I will try with watch method , but according to the documentation the methods runs every time a variable defined in the data object in the instance . Then why doesn’t it run when hover changes . I also tried it with computed why didn’t it work , computed should watch the related variables right?

Ok, here’s version with computed:

1 Like

I appreciate your solution and i think i am so near to grasping it , please clarify a little bit of my confusion. I was told that functions in the method object executes every time a variable changes and the DOM gets re-renderd. While computed functions will execute only if the dependency inside of the function is changed.

var vm = new Vue({
el: ‘.top_container’,
data: {
hover: false,
btn_img: “https://i.imgur.com/2RJTr2f.png
},
methods: {
btn_changer: function() {
if (this.hover) {

            this.btn_img = "https://i.imgur.com/ApvguGb.png"
        } else {
            this.btn_img = "https://i.imgur.com/2RJTr2f.png"
        }
    }
}})

And according to the same logic here a variable called hover changes , then why doesnot the btn_changer gets executed.

No that’s not correct. Functions in the methods are executed only when they’re called (for example on button click), regardless of variable changes.

Methods in computed are re-computed every time reactive variable changes.

Methods in watch are called when watched variable changes.