使用<a href=""> but can find it when using <img/>

时间:2019-04-27 12:23:52

标签: javascript html vue.js

I have this Vue project. All I've done is run vue create foo and removed all the pre-created code that comes in the src folder when you run that command. I then added an image to the src folder and created my own App.vue, this is all I've written in it.

<template>
  <div>
    <img alt="Vue logo" src="./foo.png">
    <a href="./foo.png" download>foo</a>
  </div>
</template>

<script>
export default {
}
</script>

When I then try it out with npm run serve the website displays the image perfectly fine, but the download link does not work. It says the server doesn't have the requested file or something.

1 个答案:

答案 0 :(得分:3)

Vue装载程序automatically transforms img src attributes in templates into webpack module requests,但默认情况下,它对链接的作用不同。

如果您需要直接链接到文件,则可以将其放在public/目录中以绕过webpack(使用相对于该目录的路径-即对于public/foo/bar.jpg中的文件,您可以d使用<a href="/foo/bar.jpg">

或者,您可以通过更改tell webpack to transform <a href> urls选项,将文件保留在原处,并将transformAssetUrls保留到模块请求中,就像图像src url一样:

/* Add to vue.config.js */
module.exports = {
    chainWebpack: config => {
        config.module
            .rule("vue")
            .use("vue-loader")
            .loader("vue-loader")
            .tap(options => {
                // modify the options...
                options = Object.assign(options, {
                    transformAssetUrls: {
                        a: "href"
                    }
                });
                return options;
            });

    }
}