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

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

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

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


米琪卡哇伊
浏览 342回答 1
1回答

慕容森

问题是没有关于模块所在位置的信息,webpack 无法解析它。不可能使用完全动态的导入语句,例如 import(foo)。因为 foo 可能是您系统或项目中任何文件的任何路径。import() 必须至少包含一些关于模块所在位置的信息。要解决此问题,您可以创建一个 BaseImage 组件来替换以特定路径开头的动态源,在本例../assets/中为 ,并让 webpack 事先知道该信息。IE。<template>&nbsp; <img&nbsp; &nbsp; :src="computedSrc"&nbsp; &nbsp; :alt="alt"&nbsp; &nbsp; class="BaseImage"&nbsp; &nbsp; v-bind="$attrs"&nbsp; &nbsp; v-on="$listeners"&nbsp; /></template><script>export default {&nbsp; name: 'BaseImage',&nbsp; inheritAttrs: false,&nbsp; props: {&nbsp; &nbsp; src: {&nbsp; &nbsp; &nbsp; type: String,&nbsp; &nbsp; &nbsp; required: true,&nbsp; &nbsp; },&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* The alt tag is required for accessibility and SEO purposes.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* If it is a decorative image, which is purely there for design reasons,&nbsp; &nbsp; &nbsp;* consider moving it to CSS or using an empty alt tag.&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; alt: {&nbsp; &nbsp; &nbsp; type: String,&nbsp; &nbsp; &nbsp; required: true,&nbsp; &nbsp; },&nbsp; },&nbsp; computed: {&nbsp; &nbsp; // If the URL starts with ../assets/, it will be interpreted as a module request.&nbsp; &nbsp; isModuleRequest() {&nbsp; &nbsp; &nbsp; return this.src.startsWith('../assets/')&nbsp; &nbsp; },&nbsp; &nbsp; computedSrc() {&nbsp; &nbsp; &nbsp; // If it is a module request,&nbsp; &nbsp; &nbsp; // the exact module is not known on compile time,&nbsp; &nbsp; &nbsp; // so an expression is used in the request to create a context.&nbsp; &nbsp; &nbsp; return this.isModuleRequest&nbsp; &nbsp; &nbsp; &nbsp; ? require(`../assets/${this.src.replace('../assets/', '')}`)&nbsp; &nbsp; &nbsp; &nbsp; : this.src&nbsp; &nbsp; },&nbsp; },}</script>替换img为BaseImage组件。<!-- <img :src="img.src"&nbsp; :alt="img.alt"> --><BaseImage :src="img.src" :alt="img.alt"/>修改后的codeandbox
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript