AlyssaAlex
AlyssaAlex

Reputation: 716

How can I switch between 2 images on click in Vue js(Nuxt)?

I am using Nuxt js and I have 2 images. When I click the first image, it should change to the second and when I click the second it should change back to the first image and so on.

This is what I have so far. I am switching between the srcs of the image like this:

<template>
<img id="test" src="../assets/menu.svg" @click="change" />
</template>

<script>
change(): any {
    const img1 = '../assets/menu.svg';
    const img2 = '../assets/cross.svg';
    const imgElement = document.getElementById('test');
    imgElement.src = imgElement.src === img1 ? img2 : img1;   <-- I think this is the problem
  }
</script>

The error on that line: Object is possibly null.

Would appreciate some help. Thanks!

Upvotes: 0

Views: 1639

Answers (1)

RobbeVP
RobbeVP

Reputation: 397

You should be able to do this with a computed property:

<template>
<img id="test" :src="imgSrc" @click="imgClicked = !imgClicked" />
</template>

<script>
  data () {
    return {
      imgClicked: false
    }
  },
  computed: {
    imgSrc: function () {
      return this.imgClicked ? '../assets/menu.svg' : '../assets/cross.svg'
    }
  }
</script>

If I remember correctly, you might have to use require if have a dynamic src: require('~/assets/menu.svg')

Upvotes: 4

Related Questions