Brian
Brian

Reputation: 27

How to pass variable inside an array Vue

How can I pass a variable from Images Array to access the display different image everytime I press the next button? I am new to vue js, I could use some help.

<template>
  <div class="background" :style="{backgroundImage: `url(${Images[number]})`}">
    <div v-on:click="next" class="nextButton"><p>&gt;</p></div>   
    </div>
  </div>
</template>

this is the array

data: () => ({
    Images:[ Image1, Image2, Image3],

this is my next script code

  methods:{
    next()
    { 
      var number = 0;

      if(number > 2){
        number == 0;
      }
      else{
        number ++;
      }
    },
  }

Upvotes: 1

Views: 67

Answers (1)

Amaarockz
Amaarockz

Reputation: 4684

The problem is everytime when you call the next method, you initialize the number to be zero. Please check the correct solution below

data: () => ({
    Images:[ Image1, Image2, Image3],
    number: 0, // Change added
    })

and the method would be like

methods:{
    next()
    { 
      if(this.number >= this.Images.length){ // Change added
        this.number = 0; // Change added
      }
      else{
        this.number += 1; // Change added
      }
    },
  }

Upvotes: 2

Related Questions