【问题标题】:Vue don't load dynamic src and require doesn't workVue 不加载动态 src 并且 require 不起作用
【发布时间】:2020-08-03 16:47:15
【问题描述】:

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

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

我已经尝试过 whit require 但它返回一个错误: Error: Cannot find module '../assets/img/banana.png'"

【问题讨论】:

标签: javascript vue.js vue-cli


【解决方案1】:

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

不可能使用完全动态的导入语句,例如 进口(富)。因为 foo 可能是任何文件的任何路径 您的系统或项目。

import() 必须至少包含一些关于 模块所在位置。

要解决此问题,您可以创建一个 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

【讨论】:

    猜你喜欢
    • 2019-03-15
    • 2019-12-12
    • 2015-10-02
    • 2019-01-18
    • 1970-01-01
    • 2019-06-26
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多