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

问题描述 投票:0回答:1

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

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>

[Codepen]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>

但是那是行不通的。它只是一遍又一遍地返回相同的第一张图像。您可以在此[codepen] https://codepen.io/daletom/pen/QWbJKPp

中看到

是否有一种雄辩的方法来传递srcset中的函数,以便以各种响应大小动态加载所有这些图像?

arrays image vue.js responsive-design responsive-images
1个回答
0
投票

问题是,每个组件只定义一个计算属性。尽管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>
© www.soinside.com 2019 - 2024. All rights reserved.