Vue 不加载动态 src 并且 require 不起作用

Vue don't load dynamic src and require doesn't work

我有问题,我想显示一个动态 img 但如果我这样写 :
<img :src="src" alt="img"> 没用,

相反,如果我这样做它会起作用: <img src="../assets/img/banana.png" alt="img">

我已经尝试过要求,但 returns 出错了: Error: Cannot find module '../assets/img/banana.png'"

问题是没有关于模块所在位置的信息,webpack无法解析。

It is not possible to use a fully dynamic import statement, such as import(foo). Because foo could potentially be any path to any file in your system or project.

The import() must contain at least some information about where the module is located.

要解决此问题,您可以创建一个 BaseImage 组件来替换以特定路径开头的动态源,在本例中为 ../assets/,并让 webpack 事先知道该信息。

<template>
  <img
    :src="computedSrc"
    :alt="alt"
    class="BaseImage"
    v-bind="$attrs"
    v-on="$listeners"
  />
</template>

<script>
export default {
  name: 'BaseImage',

  inheritAttrs: false,

  props: {
    src: {
      type: String,
      required: true,
    },

    /**
     * The alt tag is required for accessibility and SEO purposes.
     *
     * If it is a decorative image, which is purely there for design reasons,
     * consider moving it to CSS or using an empty alt tag.
     */
    alt: {
      type: String,
      required: true,
    },
  },

  computed: {
    // If the URL starts with ../assets/, it will be interpreted as a module request.
    isModuleRequest() {
      return this.src.startsWith('../assets/')
    },

    computedSrc() {
      // If it is a module request,
      // the exact module is not known on compile time,
      // so an expression is used in the request to create a context.
      return this.isModuleRequest
        ? require(`../assets/${this.src.replace('../assets/', '')}`)
        : this.src
    },
  },
}
</script>

img 替换为 BaseImage 组件。

<!-- <img :src="img.src"  :alt="img.alt"> -->
<BaseImage :src="img.src" :alt="img.alt"/>

Revised codesandbox