问题描述
我需要一个建议,
在尝试以多种方式创建支持本地lazyload的可重用图片元素组件后,我仍然陷入困境,并回退到Lazysizes.js库并接受可变数量的图像源类型和尺寸(在<source>
中和他的srcset
属性)。
要实现此目的,我希望在计算方法中使用多个require
,并且在将它们从该方法返回之前需要将它们串联起来(因为对于每个可用的图像尺寸,我都需要require
),但是我再次受到了require
的限制。
找不到img依赖项,因为我认为require
并没有像我想象的那样得到解决。这是我的代码,可帮助您理解:
// parent component
<picture-elem
:name="`${img}`"
:img-alt="`${alt}`"
:formats="['webp','jpg']"
:sizes="[['512x768','2x'],['256x384','1x']]"
:img-class="'product-img'"
:lazy="lazyloadImg" //true of false depending the context
/>
//in PictureElem component <template>
<picture>
<source
v-if="formats.indexOf('webp') != -1"
:srcset="(!lazy) ? srcsetWebp : false"
:data-srcset="(lazy && !loadingAttrSupport) ? srcsetWebp : false"
type="image/webp"
>
... // other sources element for every accepted image types
<img ... //fallback img
</picture>
//in script > computed methods,an example of the problematic part with webp
computed: {
getSizesLength () {
return this.sizes.length
},srcsetWebp () {
let srcset = ""
//loop through the array of availaible images srcset sizes
for (let i = 0; i < this.getSizesLength; i++) {
// require ( [path] + [base name] + [dimension] + [targeted resolution or screen width]
srcset += `${require(`@/assets/img/${this.name}-${this.sizes[i][0]}.webp`)} ${this.sizes[i][1]}`
// if there is following sizes,add a comma (,)
if (i < (this.getSizesLength - 1)) {
srcset += ","
}
}
return srcset
}
我总是喜欢它:
Failed to compile with 1 errors
This dependency was not found:
* @/assets/img/img-name.webp in ./node_modules/babel-loader/lib??ref--2-0!./node_modules/vue-loader/lib??vue-loader-options!./components/PictureElem.vue?vue&type=script&lang=js&
我也尝试过“〜/ assets / img / ..”
我认为问题在于串联的require
,因为我的调试检查确认了我。
我也知道一个普通人
return `${require(`@/assets/img/${this.baseName}_480.jpg`)} 480w,${require(`@/assets/img/${this.baseName}_800.jpg`)} 800w`
应该如亚历山大·利希特(Alexander Lichter)所说的那样工作: https://blog.lichter.io/posts/dynamic-images-vue-nuxt/#bonus---using-srcset
这不是我的第一种方法,我在很多文章中都根据我的发现尝试了不同的方法。这是我最后一次希望获得为该组件计划的所有灵活性和足够的干燥性...
我将尝试使用<slot>
在组件父级中定义确切的require
,但是我真的很想了解是否有一种方法可以尝试实现自己想要的功能或确认required
不能以这种方式使用(串联)。
提前感谢您的时间
解决方法
我终于发现我的问题出在其他地方,为了简化理解,问题中没有显示该部分,但是我发现您无法在路径的开头require
使用字符串变量。我这样叫:
${require(`${this.imagePath}${this.name}-${this.sizes[i][0]}.webp`)}
但是看来require
无法解决这样的路径。添加路径可解决问题:
${require(`~/assets/img/${this.name}-${this.sizes[i][0]}.webp`)}
// @/assets also works but as it is deprecated in the Nuxt docs I replaced the pointer with "~" everywhere.
请注意是否忘记编写完整路径(例如缺少/img/
部分),因为require
会尝试获取资产中的所有文件,并且会为每个资产(如字体)输出错误文件或任何其他不适合vue-loader或webpack loader的文件(我认为是这样)。