【发布时间】:2018-11-28 05:02:47
【问题描述】:
我正在学习 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 检测?
【问题讨论】:
标签: javascript laravel vue.js