【问题标题】:Calculating image sizes on load in Vue always returning zero在 Vue 中计算加载时的图像大小总是返回零
【发布时间】:2017-05-18 12:30:47
【问题描述】:

我需要计算从 Vuex 对象数组加载的多个图像的宽度总和:

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

但是,即使我直接在 mount() 方法中测试,大小也始终为零:

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

有什么方法可以强制 Vue 在所有内容渲染后获取这些尺寸?

【问题讨论】:

  • 等待图片加载?组件已加载,但图像可能尚未加载。
  • 我怎么知道所有的图片都加载了?我怎么能等到他们呢?我想当 mount() 事件被触发时,一切都已完全加载。
  • stackoverflow.com/questions/2342132/…。为每张图片设置回调函数。
  • 我明白你的意思,但我应该遍历mounted() 中的所有图像吗?那么,当所有内容都加载完毕后,我将为每个图像附加一个处理程序等等?

标签: javascript vue.js vuejs2 vuex


【解决方案1】:

我的代码中有一个类似的案例(我希望这可以进一步帮助您)在我的案例中,我想在挂载时调整画布(包含图像)的大小。我想唯一的区别是你需要循环遍历childern并求和宽度。

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()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 2017-01-11
    • 1970-01-01
    相关资源
    最近更新 更多