在NuxtJS中通过props传递的图片路径为什么无法被require()解析?
问题原因
require是webpack提供的编译期能力,只会在项目构建阶段执行路径解析,你传入完全动态的prop变量作为参数时,webpack在编译阶段无法预知运行时传入的具体路径,自然没办法完成~别名解析、资源哈希处理等操作,所以会抛出找不到模块的错误。你直接在index.vue写死路径的时候,webpack编译时能识别到静态路径,所以能正常处理。
解决方案
方案1:父组件传递预解析后的资源路径
父组件传值的时候就完成require处理,子组件直接使用即可:pages/index.vue代码修改如下:
<template> <ChildComponent :image-address="require('~/assets/icons/crown.png')" /> </template>
components/ChildComponent.vue代码修改如下:
<template> <img v-if="imageAddress.length" :src="imageAddress"> </template> <script> export default { name: 'ChildComponent', props: { imageAddress: { type: String, required: true, default: '' } } } </script>
方案2:子组件使用固定前缀拼接动态路径
如果你的图片都存放在固定目录下,可以只把文件名作为prop传递,子组件用固定路径前缀拼接后再require,webpack编译时会自动处理该目录下的所有资源:
父组件传值修改:
<template> <ChildComponent image-name="crown.png" /> </template>
子组件修改:
<template> <img v-if="imageName.length" :src="require(`~/assets/icons/${imageName}`)"> </template> <script> export default { name: 'ChildComponent', props: { imageName: { type: String, required: true, default: '' } } } </script>
方案3:使用public目录存放静态资源
把不需要webpack构建处理的图片放到项目根目录的public文件夹下,比如路径为public/icons/crown.png,直接使用绝对路径访问即可,不需要require:
父组件传值:
<template> <ChildComponent image-address="/icons/crown.png" /> </template>
子组件直接绑定src:
<template> <img v-if="imageAddress.length" :src="imageAddress"> </template>
内容的提问来源于stack exchange,提问作者amirify
相关产品推荐
相关产品推荐

