为啥在 NuxtJS 中作为 prop 传递时,图像路径没有被 require() 解析?

Posted

技术标签:

【中文标题】为啥在 NuxtJS 中作为 prop 传递时,图像路径没有被 require() 解析?【英文标题】:Why image path is not resolved by require() when passed as prop in NuxtJS?为什么在 NuxtJS 中作为 prop 传递时,图像路径没有被 require() 解析? 【发布时间】:2021-10-09 14:39:18 【问题描述】:

在我的 NuxtJS 项目中,我有一个组件接收图像路径作为道具。我尝试将其直接传递给:src="imageAddress",但它既不解决也不抛出错误。然后我尝试在require() 中使用这个路径来正确解决它。但是我收到了这个 Nuxt 错误:找不到模块'~/assets/icons/crown.png'。路径是正确的,我通过将img 元素直接放在index.vue 中进行了测试。你知道为什么会发生这种情况吗? 这就是我的代码的结构:

pages/index.vue
<template>
  <ChildComponent image-address="~/assets/icons/crown.png" />
</template>

___________________________________________________________________

components/ChildComponent.vue
<template>
  <img v-if="imageAddress.length" :src="require(imageAddress)">
</template>

<script>
export default 
  name: 'ChildComponent',
  props: 
    imageAddress: 
      type: String,
      required: true,
      default: ''
    
  

</script>

【问题讨论】:

不需要require直接添加url# @ToufiqAhmed 我在问题中提到我已经这样做了。它没有解决。它被放置在 src 中,因为它是 ~/assets/icons/crown.png。 【参考方案1】:

您可以尝试在 ChildComponent 中制作方法:

getUrl (img)  
  return require(`~/assets/icons/$img.png`);

然后在模板中:

<img :src="getUrl(imageAddress)"  />

【讨论】:

这行得通,谢谢,我使用了计算属性而不是方法。

以上是关于为啥在 NuxtJS 中作为 prop 传递时,图像路径没有被 require() 解析?的主要内容,如果未能解决你的问题,请参考以下文章