为什么在 NuxtJS 中作为 prop 传递时,require() 没有解析图像路径? [英] Why image path is not resolved by require() when passed as prop in NuxtJS?

查看:22
本文介绍了为什么在 NuxtJS 中作为 prop 传递时,require() 没有解析图像路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my NuxtJS project I have a component that recieves an image path as a prop. I tried passing it directly to :src="imageAddress" but it neither resolve nor throws an error. Then I tried to use this path inside require() to resolve it properly. But I get this Nuxt error: Cannot find module '~/assets/icons/crown.png'. The path is correct and I tested that by placing an img element directly in index.vue. Do you have any idea why this happens?
This is how my code is structured:

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>

推荐答案

可以尝试在ChildComponent中make方法:

You can try to make method in ChildComponent:

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

然后在模板中:

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

这篇关于为什么在 NuxtJS 中作为 prop 传递时,require() 没有解析图像路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆