vue3 If you are using typescript development, require will appear to import images An error is reported, require is not defined, and imgUrl: require(’…/assets/test.png’) cannot be imported like using vue2. This is because typescript does not support require
, so import is used. Here is how to solve it: Use 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 Recycle the return value to request local images
<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>
Record the problems encountered when using vue3, maybe there are other ways to solve the problem of image introduction, please give me some advice~
The latest project is vue3 vite. When using require to reference the image path, the error "require is not defined" is reported, which is very embarrassing. Because typescript does not support require, I used imgUrl directly: require(’…/assets /test.png’) will report an error when importing. You need to use import to import. Record the solution:
<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>
The above is the detailed content of vue3+vite: How to solve the error when using require to dynamically import images in src. For more information, please follow other related articles on the PHP Chinese website!