首页 > 解决方案 > vue app中重新计算srcset,元素绑定

问题描述

我正在尝试在调整窗口大小时重新计算 srcset。我的模板中有一个图片元素,如下所示:

<picture>
  <source :srcset="{path-to-image}-lg.jpg" media="(min-width: 800px)">
  <source :srcset="{path-to-image}-md.jpg" media="(min-width: 400px)">
  <img id="my_image" :src="{path-to-image}-sm.jpg">
</picture>

使用以下事件监听器:

methods: {
  setSrc () {
    if (!this.selected) return

    let width = window.innerWidth
    let img = document.getElementById('selected_image')
    let fileWithExt = img.src.split('/').pop()
    let filename = fileWithExt.split('.')[0]
    let size = filename.split('-').pop() // all images end in '-sm', '-md', '-lg'
    let picture = img.parentElement

    if (
      (width < 400 && size !== 'sm') ||
      (width >= 400 && width < 800 && size !== 'md') ||
      (width > 800 && size !== 'lg')
    ) {
      let html = picture.outerHTML
      picture.outerHTML = html
    }
  }
},
created () {
  window.addEventListener('resize', this.setSrc)
},
beforeDestroy () {
  window.removeEventListener('resize', this.setSrc)
}

事件侦听器完美地处理调整大小/媒体查询图像选择,但是,我意识到替换图片的 html 正在替换绑定到 vue 的 DOM 中的一个元素,而不是一个。所以我想我反对的是:

  1. 有没有更好的方法来处理调整大小以使用 Vue 重新计算 srcset?
  2. 如果这最终是处理调整大小的最佳方式,有没有办法将图片元素重新绑定到 Vue?

标签: javascripthtmlvue.js

解决方案


@HusamIbrahim所以我想使用为这种事情制作的原生html5元素,但由于我必须添加一些事件监听来动态设置键,我最终决定只用v-if处理整个事情, else-if, else

更新到模板:

<img v-if="breakpoint === 800" :src="selected.sizes.xl">
<img v-else-if="breakpoint === 400" :src="selected.sizes.lg">
<img v-else :src="selected.sizes.md">

我添加了breakpointdata 属性并使用此getBreakpoint方法动态设置它,我调用并为 on 设置事件侦听器created()

getBreakpoint () {
  // if the window width divided by 400 rounded down returns a valid index
  // 0 thru 2, return the array item, else hardcode index to 2 and return 800
  this.breakpoint = [0, 400, 800][Math.floor(window.innerWidth / 400) <= 2 ? Math.floor(window.innerWidth / 400) : 2]
}

推荐阅读