Home  >  Article  >  Web Front-end  >  What should I do if I get an error when introducing absolute paths in vue?

What should I do if I get an error when introducing absolute paths in vue?

藏色散人
藏色散人Original
2023-01-29 14:57:011984browse

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.

What should I do if I get an error when introducing absolute paths in vue?

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(&#39;&#39;);
            const handleImgSrc = async()=>{
                let m = await import(&#39;@/assets/img/22.png&#39;);
                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: &#39;a.png&#39;},{url: &#39;b.png&#39;},{url: &#39;c.png&#39;}
])
             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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn