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 중국어 웹사이트의 기타 관련 기사를 참조하세요!