javascript - 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 中的一个元素,而不是一个。所以我想我反对的是:
- 有没有更好的方法来处理调整大小以使用 Vue 重新计算 srcset?
- 如果这最终是处理调整大小的最佳方式,有没有办法将图片元素重新绑定到 Vue?
解决方案
@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">
我添加了breakpoint
data 属性并使用此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]
}
推荐阅读
- php - 如何更改物化上的对齐方式
- coq - 如何证明 forall (pq:Prop), ~p->~((p ->q) ->p)。使用 coq
- java - 多线程延迟的原因
- java - 使用 Livedata 并在显示 MutableLiveData 时遇到问题
结果 - generics - 当作为参数传递时,in/out 在 Kotlin 中实际上做了什么?
- c++ - 如何在不使用指针的情况下搜索特定字符的数组结构
- python - 管理站点中消失的蛞蝓
- android - 无法启动模拟器:错误:模拟器未在 60 秒内连接
- python - Sotfmax 的导数是否有任何适当的 numpy 函数?
- python - 如何修复 numpy python 文件加载/写入中的逻辑错误