Home >Web Front-end >Front-end Q&A >What should I do if I get an error when introducing absolute paths in vue?
Solution to the error when introducing absolute paths in vue: 1. Use "await import('@/assets/img/22.png');" to introduce the path; 2. Recycle the return value to request local images That’s it.
The operating environment of this tutorial: Windows 10 system, vue3 version, DELL G3 computer
What should I do if I get an error when introducing absolute paths into vue?
vue3 vite:src Use require to introduce an absolute path and report an error
The most recent 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, so I used imgUrl directly: require('.../assets/test.png') before importing, and an error will be reported. You need to use import to import. Record the solution:
First method: 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>
Second type: 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>
Recommended learning: "vue video tutorial 》
The above is the detailed content of What should I do if I get an error when introducing absolute paths in vue?. For more information, please follow other related articles on the PHP Chinese website!