sucaiking
V2EX  ›  Vue.js

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

  •  
  •   sucaiking · Dec 4, 2023 · 1755 views
    This topic created in 914 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
        1
    lisongeee  
       Dec 4, 2023
    提前将 D:/vueproject/code 的 图片文件 使用 require.context 按需加载

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

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