【问题标题】:Nuxt 3: Programmatically Access /public FilesNuxt 3:以编程方式访问/public 文件
【发布时间】:2022-12-03 01:30:45
【问题描述】:

我有一个使用 Nuxt 3 的项目,在 /public 目录(和子目录)中有很多图像。现在我想实现一个简单的图库,显示目录(或指定子目录)中的所有图像。有没有办法以编程方式访问目录中的所有文件,这样我就可以做这样的事情:

<script setup>
let images = ???
</script>

<template>
  <img v-for="image in images" :key="image.path" :scr="image.path" alt="" />
</template>

【问题讨论】:

  • 据我所知,无法在运行时访问目录结构,同时您可能可以在构建时执行此操作并将数据以某种方式传递给您的代码。

标签: javascript vue.js nuxt.js nuxtjs3


【解决方案1】:

是的,您可以使用 require.context() 方法以编程方式访问 Nuxt.js 项目中 /public 目录中的文件。此方法允许您指定要搜索的目录,并返回一个对象,其中包含有关该目录中所有文件的信息。

下面是一个示例,说明如何使用此方法访问 /public 目录中的文件:

<script>
import { requireContext } from '@nuxt/utils'

// Use require.context() to search the /public directory for files
const imagesContext = requireContext('@/public', true, /.(png|jpeg|jpg|gif)$/)

// Get the path and name of each image file
const imagePaths = imagesContext.keys()
const imageNames = imagePaths.map(path => imagesContext(path).default)

export default {
  data() {
    return {
      images: imageNames
    }
  }
}
</script>

<template>
  <img v-for="image in images" :key="image.path" :src="image.path" alt="" />
</template>

在此示例中,我们使用 require.context() 方法在 /public 目录中搜索图像文件(扩展名为 .png、.jpeg、.jpg 和 .gif)。然后我们使用 keys() 方法获取每个文件的路径和名称,并将这些值存储在图像数组中。

最后,在模板中,我们循环遍历图像数组并为每个图像渲染一个元素,使用每个图像的路径属性作为 src 属性。

【讨论】:

  • 我刚刚试过了,Nuxt 告诉我这个文件/函数不存在。你确定它在 Nuxt 3 中仍然是这样工作的吗?
【解决方案2】:

您可以使用可组合项执行以下操作

composables/useAssets.js

import fs from 'fs';
import path from 'path';

const folderPath = './public';
const relativeFolderPath = path.relative(process.cwd(), folderPath);

export default function () {
  const files = fs
    .readdirSync(folderPath)
    .filter((file) => file.match(/.*.(jpg|png?)/gi));

  const filesPaths = files.map(
    (fileName) => `/_nuxt/${relativeFolderPath}/${fileName}`
  );

  return filesPaths;
}

YourComponent.vue

<script setup>
  const assets = useAssets();
</script>

<template>
  <div>
    <img :src="item" v-for="item in assets" :key="item" />
 </div>
</template>

您基本上是通过配置 folderPath 读取指定文件夹中的所有文件,然后从根目录获取该文件夹的相对路径,稍后将其附加到文件路径(process.cwd() 获取根项目路径)。

在获取匹配的资产并将数组存储在files 之后,我们使用map 构造一个具有正确文件相对路径的新数组,以便 nuxt 正确读取它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多