Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? Thank you

like image 616
Miguel Stevens Avatar asked Mar 14 '23 09:03

Miguel Stevens


1 Answers

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

like image 51
Ricardo Avatar answered Mar 23 '23 07:03

Ricardo