繁体   English   中英

Nuxt / vite 中的动态资产

[英]Dynamic assets in Nuxt / vite

我可以简单地使用以下方法从 Nuxt (+ webpack) 中的文件夹动态加载图像:

getServiceIcon(iconName) {
  return require ('../../static/images/svg/services/' + iconName + '.svg');
}

我搬到了 Vite,这里没有定义require (使用汇总)。 我该如何解决这个问题,使用 nuxt / vite? 任何想法?

您可以像这样使用import()

const getServiceIcon = async iconName => {
  const module = await import(/* @vite-ignore */ `../../static/images/svg/services/${iconName}.svg`)
  return module.default.replace(/^\/@fs/, '')
}

演示 1:Vue 3 组合 API

演示 2:Vue 3 选项 API

演示 3:Vue 2 组合 API

演示 4:Vue 2 选项 API

@tony19 的回答返回错误。 我设法在 Nuxt 3 中使用import() 、VueUse 的computedAsync()Promise.all()让它工作。

这是毫无疑问的最丑陋的解决方法,但它适用于我的机器。

const _brands = [
  { name: 'Logo 1', logo: 'logo1.svg' },
  { name: 'Logo 2', logo: 'logo2.svg' },
];

// make an array of import promises
const logoUrls = _brands.map((brand) =>
  import(`../assets/images/brands/${brand.logo}`)
);

// import computedAsync (auto-imported in my case)
// use it to reactively update after promise resolves
// read more at VueUse
const brands = computedAsync(async () => {
  let result;

  // Promise.all => run many promises in parallel and wait till all of them are ready
  await Promise.all(logoUrls)
    // remove '@fs/'
    .then((rawUrls) =>
      Promise.all(rawUrls.map((ru) => ru.default.replace(/^\/@fs/, '')))
    )
    .then((urls) => {
      // map out to your original structure
      result = _brands.map((soc) => {
        const { name, logo } = soc;
        const logoUrl = urls.find((u) => u.endsWith(logo));
        return { name, logo: logoUrl };
      });
    });

  return result;
}, null);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM