2

I need to calculate the sum of widths of a number of images which are loaded from a Vuex array of objects:

   var activities = [
        {
            id: 1,
            imageUrl: '/static/images/activity1.jpg',
        },
        {
            id: 2,
            imageUrl: '/static/images/activity2.jpg',
        }
    ]

However, the sizes are always zero, even if I test it directly in the mounted() method:

    mounted: function() {
        console.log(document.getElementById('scroller-list').children[0].firstChild.offsetWidth)
    },

Is there any way to force Vue to fetch those sizes after everything has rendered?

Anonymous
  • 850
  • 2
  • 12
  • 26
  • Wait for the images to load? The component has loaded, but the images probably haven't. – Eric Guan May 18 '17 at 15:37
  • How can I know that all the images have loaded? And how can I wait for them? I thought when the mounted() event was fired everything was completely loaded. – Anonymous May 18 '17 at 16:22
  • http://stackoverflow.com/questions/2342132/waiting-for-image-to-load-in-javascript. Set a callback function for each image. – Eric Guan May 18 '17 at 17:38
  • I see your point, but should I loop through all the images inside mounted()? So, when everything is loaded, I'll attach a handler to each image and so on? – Anonymous May 19 '17 at 01:25

1 Answers1

0

I have a similar case within my code (I hope this can help you further) In my case I want to resize an canvas (which holds a image), at mounted. I guess the only difference is that you will need to loop over the childern and sum the width.

methods: {
    resizeCanvas () {
       var ratio = Math.max(window.devicePixelRatio || 1, 1)
       var canvas = document.querySelector('canvas')
       if (canvas) {
         canvas.width = canvas.offsetWidth * ratio
         canvas.height = canvas.offsetHeight * ratio
         canvas.getContext('2d').scale(ratio, ratio)
       }
     }
   }


mounted () {
  const canvas = document.querySelector('canvas')

  window.addEventListener('resize', this.resizeCanvas)
  this.resizeCanvas()
}
M. Suurland
  • 725
  • 12
  • 31