Making a picture clickable in Vuejs

Viewed 14417

I have a picture that I want to be clickable. I tried both

<img @click="myMethod" src="hasan.jpg"> 

and

<div @click="myMethod">
   <img src="hasan.jpg">
</div>

but neither worked! What's the best way to do it?

Here is the complete code:

<template>
  <div @click="myMethod">
   <img src="hasan.jpg" id="hasanStyle">
  </div>
</template>

<script>
export default{
  data(){
    return{
      showHasan:true
    }
  },
  methods:{
    myMethod(){
      showHasan = false
    }
  }
}
</script>

<style scoped>
  #hasanStyle{
    position: absolute;
    top: 120px;
    right: -323px;
  }
</style>
2 Answers

Don't know if you tried this :

First there is problem ->

methods:{
    myMethod(){
      showHasan = false
    }
  }

Above code should be :

    methods:{
        myMethod(){
          // because you are accessing data property of vue instance and 
// every vue instance make the proxy of data object as a root.
          this.showHasan = false
        }
      }

Second when you use myMethod try to use console.log or alert that will confirm you your method is working on image or div.

or Have a look jsfiddle code :

new Vue({
  el: "#app",
  data: {
   showHasan: true
  },
  methods: {
   myMethod () { 
     this.showHasan = false
    }
  }
})
<div id="app">
   <div @click="myMethod">
     <img v-if="showHasan" src="https://pbs.twimg.com/profile_images/972154872261853184/RnOg6UyU_400x400.jpg" id="hasanStyle">
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>

Have you tried:

<div onClick="myMethod()">
   <img src="hasan.jpg" id="hasanStyle">
</div>

myMethod should be a method of course

Related