Vue cli 3 项目,图像路径中的动态 src 不起作用

Sai*_*S.R 4 assets webpack vue.js webpack-dev-server vue-cli-3

我在 vue 组件中引用图像 url,例如

<img alt="Vue logo" src="~statics/reports/logo.png">
Run Code Online (Sandbox Code Playgroud)

这有效

但在尝试的同时

<img alt="Vue logo" :src="getURL()">


data() {
    return { imgPath: "~statics/reports/logo.png" };
  },

  methods: {

    getURL() {
        // 

      // console.log(path)
      return (this.imgPath)
    }
  },
Run Code Online (Sandbox Code Playgroud)

它失败

我的文件夹结构是 在此处输入图片说明

在第一种情况下,路径被解析为

http://localhost:8081/img/logo.82b9c7a5.png
Run Code Online (Sandbox Code Playgroud)

并由开发服务器自动提供

在第二种情况下,路径未解析,它仍然存在 http://localhost:8081/~statics/reports/logo.png

我正在使用 vue cli 3 为 webpack 生成的默认配置。

我不想对像 ../images/ 这样的所有图像使用相对路径,因为它使它更加冗长。我试过 require(pathVariable) 也不起作用当 url 是动态的,即资产名称来自服务器时,请帮助解析 img 路径,我在方法或计算中附加路径并使用 :src 动态绑定来提供服务

ach*_*lko 15

The second way fails because "~" try to get this asset from node_modules. You can read more about handling assets here: https://cli.vuejs.org/guide/html-and-static-assets.html#relative-path-imports.

To fix it just use require like below:

data() {
  return {
    imgPath: require('@/statics/logo.png')
  }
}
Run Code Online (Sandbox Code Playgroud)

..or directly in template:

<img alt="Vue logo" :src="require('@/statics/logo.png')">
Run Code Online (Sandbox Code Playgroud)