Show an image for an order GET Ajax (axios) of vue js 2 and show it by html 5

2

This is my code I want to make a call get of axios by vue and that after having the image that shows it in html

        getImage(param) {
            axios.get(param)
            .then((resp) => {
                return this.image  = resp.data;
            }).catch((err)=>{
                console.log(err)
            });
        }

html (it's actually the vue template but it goes inside an html 5)

               <picture>
                <img
                    src= getImage(auto.car.images.file) > // suponiendo que file contiene una url que lleva al lugar de la pagina contenedora de la imagen
                </picture>
    
asked by Hernan Jesus Diaz Yarbi 23.06.2017 в 02:23
source

1 answer

1

The problem is that you are putting in the attribute src the status of a promise ( [pending] ); remember well, a Promise is asynchronous and a callback is also; do not expect it to be available in the caller what returns a promise or a callback because you will not get the expected value.

What you should do is to make a bind of src to a variable or property of an object and then, execute the method that getImage to update said variable with the obtained image and that it is automatically reflected in the HTML.

Example

new Vue({
  data: function() {
    return {
      profilepic: null,
    };
  },
  methods: {
    getImage(url) {
      this.profilepic = 'https://widgetsdataifx.blob.core.windows.net/widgetsdataifx/Content/themes/Davivienda/images/loading_spinner.gif';
      return axios.get(url, { responseType: 'arraybuffer' });
    },
  },
  mounted() {
    this
      .getImage('https://crossorigin.me/https://ih1.redbubble.net/image.109336634.1604/flat,550x550,075,f.u1.jpg')
      .then(({ data }) => {
        // simulamos una carga
        setTimeout(() => {
        // convertimos el buffer en base64
        const image = btoa(
          new Uint8Array(data)
            .reduce((acc, byte) => acc + String.fromCharCode(byte), '')
        );
        this.profilepic = 'data:image/png;base64,${image}';
        }, 1500);
      });
  },
}).$mount('#app');
img {
  border: 4px solid #ccc;
  border-radius: 4px;
  display: block;
  height: 100px;
  margin: 25px auto;
  width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.min.js"></script>

<div id="app">
  <img :src="profilepic" />
</div>
    
answered by 30.06.2017 / 15:15
source