sucaiking
V2EX  ›  Vue.js

如何在 vue 项目中,正确引用项目文件夹外的图片

  •  
  •   sucaiking · Dec 4, 2023 · 2251 views
    This topic created in 1073 days ago, the information mentioned may be changed or developed.

    我并不想把一些图片放在/src 里,于是我试着创建了一个和项目 vue_code 同级的文件夹 photoData ,把图片放在里面。现在我打开网页时好像没法正确获取图片。

    经过查找资料,我现在使用的写法是:

    <img v-for="photo in photos" :key="photo.photo_id" :src="require('D:/vueproject/code' + photo.photo_path)" />

    但这种写法似乎会导致运行时需要 build 的 modules 数无限增大。请问下我正确的写法应当是什么。

    6 replies  •  2023-12-05 21:12:45 +08:00
    lisongeee
    lisongeee
    Dec 4, 2023
    1
    提前将 D:/vueproject/code 的 图片文件 使用 require.context 按需加载

    如果是 vite 可以使用 import.meta.glob
    cuttlefish
    cuttlefish
    Dec 5, 2023
    2
    不大明白,这样子引入目的是为了啥。
    coolcoffee
    coolcoffee
    Dec 5, 2023❤️1
    3
    你这种依赖系统路径的项目,换个电脑要怎么跑?

    你为啥不把图片文件都放在 public 目录里面,然后用 “/” 路径直接访问,或者是直接丢 oss+cdn 直接全外部依赖。
    flyqie
    flyqie
    Dec 5, 2023 via Android
    4
    无论如何都不要在项目源码里使用绝对路径。
    nashaofu
    nashaofu
    Dec 5, 2023 via Android
    5
    require.context 好像可以,很久没用了
    sucaiking
    sucaiking
    OP
    Dec 5, 2023
    6
    感谢各位坛友。几番试错后我发现自己一开始的想法及其离谱,用../去找父目录也很蠢。作为不需要太过讲究的课程作业,我最后的解决方案是用 http-server 起了个本地服务器,配置好端口之后用作图片源。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2322 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 13:27 · PVG 21:27 · LAX 05:27 · JFK 08:27
    ♥ Do have faith in what you're doing.