我正在学习Vue.js.在我的网站上,我有两种格式的相同图像 - jpg和webp . 我想通过一些过滤器生成正确的图像链接取决于浏览器支持(有或没有.webp) . 我现在不需要进行此检测,我只想知道在Vue中设置“background-image”和img“src”的最佳方法是什么 .
这就是我现在拥有的:
<template>
<div>
<div v-bind:style="{ backgroundImage: 'url(' + webp('/images/demo.jpg') + ')' }">
<div class="container" style="min-height: 520px">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card card-default">
<div class="card-header">Example Component</div>
<div class="card-body">
<img v-bind:src="'/images/demo2.jpg' | webp">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
methods: {
webp(url) {
// here will be code to detect webp support
return url + '.webp';
}
},
filters: {
webp(url) {
// here will be code to detect webp support
return url + '.webp';
}
},
mounted() {
console.log('Component mounted.')
}
}
</script>
它有效,但这是正确的方法吗?第一个问题是我尝试使用过滤器,因为它对我来说看起来更干净 . 在img src中它可以工作,但在v-bind:style我必须使用方法 . 现在在脚本中我有单独的方法和过滤器做同样的,这是坏的...我试图使用过滤器,但这不起作用:
<div v-bind:style="{ backgroundImage: 'url(' + '/images/bg.jpg' | webp + ')' }">
我不需要动态更改图像,所以我尝试使用标准样式并使用小胡子:
<div style="background-image: url({{ '/images/bg.jpg' | webp }} ">
但这会导致“内部属性内插已被删除” .
什么是实现这一目标的最佳,正确和干净的方法,所以我可以在background-image和img src中使用我的webp检测?
1 回答
不确定这是否适合您,但我认为this Kirby CMS plugin处理WebP的方式很聪明 - 它检测到服务器配置中的WebP支持并将任何请求重定向到
*.jpg
到*.webp
. 此示例适用于Apache,但应该可以采用与其他服务器类型相同的方法 .