vue3 如果使用的是typescript开发,就会出现require引入图片报错,require is not defined 不能像使用vue2 这样imgUrl: require(’…/assets/test.png’) 导入,是因为typescript不支持require
所以用import导入,下面介绍如何解决: 使用await import(’@/assets/img/22.png’);
<template> <img :src="imgUrl" alt=""> </template> <script> import {ref, onMounted} from "vue"; export default { name: "imgPage", setup(){ onMounted(()=>{ handleImgSrc(); }) const imgUrl = ref(''); const handleImgSrc = async()=>{ let m = await import('@/assets/img/22.png'); imgUrl.value = m.default; }; return{ imgUrl } } } </script>
demo2.vue 循环利用返回值请求本地图片
<template> <img v-for="item in imgList" :src="getAssetsImages(item.url)" alt=""> </template> <script> import {ref, reactive, onMounted} from "vue"; export default { name: "imgPage", setup(){ const imgList = reactive([ {url: 'a.png'},{url: 'b.png'},{url: 'c.png'} ]) const getAssetsImages =(name)=> { return new URL(`/src/assets/pic/${name}`, import.meta.url).href; //本地文件路径 } return{ imgList , getAssetsImages } } } </script>
记录一下使用vue3遇到的问题,或许还有别的办法解决图片引入问题,还请各位指教~
最近的项目是vue3+vite,在使用require引用图片路径的时候就报错 require is not defined,就很尴尬,因为typescript不支持require所以之前直接用imgUrl: require(’…/assets/test.png’) 导入就会报错需要用import导入,记录一下解决方法:
<template> <img :src="imgUrl" alt=""> </template> <script> import {ref, onMounted} from "vue"; export default { name: "imgPage", setup(){ onMounted(()=>{ handleImgSrc(); }) const imgUrl = ref(''); const handleImgSrc = async()=>{ let m = await import('@/assets/img/22.png'); imgUrl.value = m.default; }; return{ imgUrl } } } </script>
<template> <img v-for="item in imgList" :src="getAssetsImages(item.url)" alt=""> </template> <script> import {ref, reactive, onMounted} from "vue"; export default { name: "imgPage", setup(){ const imgList = reactive([ {url: 'a.png'},{url: 'b.png'},{url: 'c.png'} ]) const getAssetsImages =(name)=> { return new URL(`/src/assets/pic/${name}`, import.meta.url).href; //本地文件路径 } return{ imgList , getAssetsImages } } } </script>
以上是vue3+vite:src使用require动态导入图片报错怎么解决的详细内容。更多信息请关注PHP中文网其他相关文章!