orangeman
orangeman

Reputation: 53

How to get images to automatically reload in a vue component

I'm pretty new to Vue, I have an app running with a few different pages. One of the pages I'm trying to have is one that displays all images that are found in a directory on my host and to have them auto reload whenever the image changes (a separate app updates these images every 10 seconds). I've been able to display all the images (although only by listing them) and I can't seem to figure out how to get the pictures to auto refresh. Below is the code, any help is much appreciated.

<template>
  <div id="app" class="media-display">
    <figure class="media-post" v-for="(image, index) in images" v-bind:key="image.id" >
      <img :key="index" :src="getImage(index)" v-bind:alt="image" width="580" height="390" v-bind:key="index" />
    </figure>
  </div>
</template>

<script>
import moment from 'moment'

export default {
  el: '#app',
  data(){
    return {
      images: [
        '/charts/chart1.png?rnd='+Math.random(),
        '/charts/chart2.png?rnd='+Math.random(),
        '/charts/chart3.png?rnd='+Math.random(),
      ],
      id : 1,
    }
  },
  methods: {
    getImage(index) {
      return this.images[index]
    }
  }
}
</script>

<style>
.media-post {
  display: inline-block;
  padding: 1vmin;
  //border-radius: 2vmin;
  box-shadow: 0 10px 5px rgba(0, 0, 0, 0.2);
  margin: 0;
  background: #FFF;
  position: relative;
  cursor: pointer;
}
.media-post img {
  //border-radius: 1vmin;
  display: block;
  max-width: 100%;
  height: auto;
}
.media-post figcaption {
  color: #FFF;
  position: absolute;
  top: 0;
  left: 0;
  font-weight: bold;
  padding: 1rem 1.5rem;
  z-index: 2;
  font-size: 2rem;
  text-shadow: 0 1px 2px #000;
}
</style>

Upvotes: 3

Views: 7652

Answers (1)

Decade Moon
Decade Moon

Reputation: 34286

You just need to regenerate the random number suffix periodically. Untested:

<img
  v-for="url of images"
  :key="url"
  :src="url + '?rnd=' + cacheKey"
/>
data() {
  return {
    images: [
      '/charts/chart1.png',
      '/charts/chart2.png',
      '/charts/chart3.png',
    ],
    cacheKey: +new Date(),
  };
},

created() {
  this.interval = setInterval(() => {
    this.cacheKey = +new Date();
  }, 60 * 1000);
},

destroyed() {
  clearInterval(this.interval);
},

If it isn't clear, +new Date() returns the number of seconds since 1 January 1970 00:00:00 UTC (docs).

Upvotes: 10

Related Questions