在Vue.js中将img srcset与数组和数据对象绑定



我有一个数组中的图像名称列表,但我想在它们前面加一个主机,并添加一些有趣的大小调整选项以进行响应。这是我所拥有的:

new Vue({
el: '#gallery_images',
data: {
desktop: 'w=400&h=400&fit=crop&crop=faces,entropy&auto=format,compress 400w,',
ipad: 'w=600&h=600&fit=crop&crop=faces,entropy&auto=format,compress 600w,',
mobile: 'w=900&h=900&fit=crop&crop=faces,entropy&auto=format,compress 900w,',
responsive: 'w=1200&h=1200&fit=crop&crop=faces,entropy&auto=format,compress 1200w',
host: 'https://tom.imgix.net/artsy/',
images: [ '1.jpg?', '2.jpg?', '3.jpg?', '4.jpg?', '5.jpg?', '6.jpg?']
}
});

我能够在html中进行一些笨拙的v-bind,这很有效:

<div id="gallery_images">  
<img v-for="image, in images" :src="'https://tom.imgix.net/artsy/' + image" v-bind:srcset="host + image + desktop + host + image + ipad + host + image + mobile + host + image + responsive" sizes="(min-width: 1240px) 33vw, 100vw"/>
</div>

[代码笔]https://codepen.io/daletom/pen/WNvNgOa这确实有效!但我认为还有更好的方法。而不是必须写所有这些主机+图像+大小+主机+图像+大小。如果我能为它做一个功能,并在我的网站上的所有页面上轻松使用它,那就太好了。

所以我试着建造这个。我在想也许可以添加一个计算函数:

computed: {
vueSDK: function () {
return this.host + this.images + this.desktop + this.host + this.images + this.ipad + this.host + this.images + this.mobile + this.host + this.images + this.responsive
}
}

然后只需传递srcset中的函数:

<div id="gallery_images">  
<img v-for="image, in images" :src="host + image" v-bind:srcset="vueSDK" sizes="(min-width: 1240px) 33vw, 100vw"/>
</div>

但这行不通。它只是一遍又一遍地返回相同的第一个图像。你可以在这个[代码笔]中看到https://codepen.io/daletom/pen/QWbJKPp

有没有一种有效的方法可以在srcset中传递一个函数,以动态加载所有这些具有各种响应大小的图像?

问题是,每个组件只定义一个单独的计算属性。然而,v-for需要为每个迭代计算一个属性。最简单的方法是使用方法而不是计算变量(缺点是丢失了计算变量的缓存(。如果循环遍历子组件,那么每个子组件中也可以有一个计算变量。我更喜欢第二种选择。以下是这两个选项的示例:

使用方法

<template>
<img v-for="image in images" :src="host + image" :srcset="getSrcset(image)" sizes="(min-width: 1240px) 33vw, 100vw" />
</template>
<script>
export default {
data () {
return {
host: ...,
images: ...
}
},
methods: {
getSrcset () {
return ...;
}
}
};

使用子组件

在父组件中:

<custom-image v-for="image in images" :image="image" />

以及子组件:

<template>
<img :src="host + image" :srcset="srcset" sizes="(min-width: 1240px) 33vw, 100vw" />
</template>
<script>
export default {
props: 'image',
data () {
return {
host: ...
}
},
computed: {
srcset () {
return ...
}
}
};
</script>

最新更新