如何让图像在 vue 组件中自动重新加载

ora*_*man 0 vue.js vue-component vuetify.js

我对 Vue 很陌生,我有一个运行着几个不同页面的应用程序。我试图拥有的页面之一是显示在我的主机上的目录中找到的所有图像,并在图像更改时自动重新加载它们(单独的应用程序每 10 秒更新一次这些图像)。我已经能够显示所有图像(虽然只是通过列出它们),但我似乎无法弄清楚如何让图片自动刷新。以下是代码,非常感谢任何帮助。

<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>
Run Code Online (Sandbox Code Playgroud)

Dec*_*oon 6

您只需要定期重新生成随机数后缀。未经测试:

<img
  v-for="url of images"
  :key="url"
  :src="url + '?rnd=' + cacheKey"
/>
Run Code Online (Sandbox Code Playgroud)
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);
},
Run Code Online (Sandbox Code Playgroud)

如果不清楚,则+new Date()返回自 1970 年 1 月 1 日 00:00:00 UTC ( docs )以来的秒数。