1 回答

TA貢獻1853條經驗 獲得超18個贊
問題是沒有關于模塊所在位置的信息,webpack 無法解析它。
不可能使用完全動態的導入語句,例如 import(foo)。因為 foo 可能是您系統或項目中任何文件的任何路徑。
import() 必須至少包含一些關于模塊所在位置的信息。
要解決此問題,您可以創建一個 BaseImage 組件來替換以特定路徑開頭的動態源,在本例../assets/中為 ,并讓 webpack 事先知道該信息。
IE。
<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"/>
修改后的codeandbox
添加回答
舉報