Search code examples
javascriptvue.jsvuejs2vue-componentvuex

Vue.js - how to hide an image with the hover event on it and show another?


I have two images whose behavior I want to see next. By default the image will be shown with the name 'home' and with the event 'mouseover' I want to hide and show the image with the name 'blackhome'. I have the two images shown on screen and there's nothing happens with the mouse events I don't know if this is possible. Here's a codepen link with the issue https://codepen.io/CharlieJS/pen/gOrayzW

this is my template

                      <li class="nav-item" @mouseover="homeLink = !homelink" @mouseleave="!homeLink" >
                        <a class='nav-link home'  href="https://www.google.com/">
                        <img v-if="homeLink" class="logo" src="../../assets/home.png">
                        <img v-if="!homelink" src="../../assets/blackhome.png">
                        </a>
                      </li>

and my script

export default {
  data: function () {
    return {
     
      homeLink: false
    }
  },
  computed: {
      auth () {
        return this.$store.getters.isAuthenticated
      }
    },
  methods: {
    onLogout() {
      this.$store.dispatch('logout')
    },
  }
}
</script>


Thank you in advance for your time and help


Solution

  • Try v-if and v-else as follows :

    <li class="nav-item" @mouseover="homeLink = !homelink" @mouseleave="homeLink=false" >
      <a class='nav-link home'  href="https://www.google.com/">
         <img v-if="homeLink" class="logo" src="../../assets/home.png"/>
        <img v-else src="../../assets/blackhome.png"/>
       </a>
    </li>
    

    let app = new Vue({
      el: "#app",
      data: function() {
        return {
    
          homeLink: false
        }
      },
    
    })
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <div id="app">
      <li class="nav-item" @mouseover="homeLink = !homelink" @mouseleave="homeLink=false">
        <a class='nav-link home' href="https://www.google.com/">
          <img v-if="homeLink" class="logo" src="https://picsum.photos/300/200?image=244" />
          <img v-else src="https://picsum.photos/300/200?image=1024" />
        </a>
      </li>
    </div>