Miguel Stevens
Miguel Stevens

Reputation: 9191

Vuejs get image from remote source

I'm using the following code to detect a button click, and get an image from unsplash which features a random mode.

The problem is it works one time, to fetch a random one. But the second time it's not changing..

It's not re-requesting it, it's just not changing it because it's same URL I think.

var vue = new Vue({
  el: '#app',
  data: {
    styleObject: {
        background: 'url(https://unsplash.it/1920/1080)'
    }
  },
  methods: {
    getImage: function() {
        vue.styleObject.background = 'url(https://unsplash.it/1920/1080?random)'
    }
  }
})

I tried erasing the variable

getImage: function() {
    vue.styleObject.background = '';
    vue.styleObject.background = 'url(https://unsplash.it/1920/1080?random)'
}

But still no success, Any ideas?

Upvotes: 5

Views: 1699

Answers (1)

Ricardo
Ricardo

Reputation: 124

You can try to make some cache braking. I think that it is your browser that is caching the request and serving you with the same image. Try to append a random string at the end of the request like this:

 methods: {
    getImage: function() {
        var max = 90000;
        var min = 10000;
        var slug = Math.random() * (max - min) + min;
        vue.styleObject.background = 'url(https://unsplash.it/1920/1080?random&s=' + slug +')';
    }
  }

Hope this helps

Upvotes: 8

Related Questions