Home > Back-end >  Using element from single object in list as img source in Vue.js
Using element from single object in list as img source in Vue.js

Time:12-04

I have a list of objects, which for now only contain an id and a path:

export let carList = [
    {
        id :   id,
        path : "img/RedCar.png",
    },
    {
        id :   id,
        path : "img/BlueCar.png",
    },
    {
        id :   id,
        path : "img/GreenCar.png",
    },
]

and would like to display them one at a time based on an index that can be incremented with buttons. So far I have managed to print them all out using v-for but can't seem to find a way to only print one. This is what I have so far:

<template>
<div id="carSelector">
    <img id="left-arrow" src="img/leftarrow.png">
    <img id="carPic" v-for="car in cars" :src="car.path" v-bind:key="car.id" />
    <img id="right-arrow" src="img/rightarrow.png">
</div>
</template>

<script>
import {carList} from './page-index.js'

export default {
    name: "carSelector",
    data() {
        return {
            cars: carList
        }
    },
    methods: {
    
    }
}
</script>

CodePudding user response:

You can take a variable to maintain the current index and add two functions to toggle between the images. I hope this solves your problem.


<template>
  <div id="carSelector">
    <img id="left-arrow" src="img/leftarrow.png" @click="previous"/>
    <img id="carPic" :src="cars[selectedIndex].path" />
    <img id="right-arrow" src="img/rightarrow.png" @click="next" />
  </div>
</template>
<script>
import { carList } from "./page-index.js";
export default {
  name: "carSelector",
  data() {
    return {
      selectedIndex: 0,
      cars: carList,
    };
  },
  methods: {
    next() {
      if (this.selectedIndex < this.cars.length) {
        this.selectedIndex  ;
      }
    },
    previous() {
      if (this.selectedIndex !== 0) {
        this.selectedIndex--;
      }
    },
  },
};
</script>
  • Related