skip to Main Content

Now I’m building a vue3 project in vite. But I found a weird error.

The following code work perfectly:

<template>
  <img src="@/assets/images/pics/cover_info.jpeg">
</template>
<script>
export default {
  name: 'Image',
  data() {
  return {
    
  };
}
};
</script>

While I change to v-bind, the server failed to load the img

<template>
  <img :src="ImgUrl">
</template>
<script>
export default {
  name: 'Image',
  data() {
  return {
    ImgUrl: '@/assets/images/pics/cover_info.jpeg',
  };
}
};
</script>

the console show following info:
GET http://localhost:5173/assets/images/pics/cover_info.jpeg 404 (Not Found)

Thank you for your patient and hope for your reply.

2

Answers


  1. When loading dynamic files, because they first have to go through the bundlers – vite, webpack, e.tc. So, your implementation should be;
    <img :src="ImgUrl" />.

    <template>
     <img :src="ImgUrl">
    </template>
    <script>
     export default {
     name: 'Image',
     data(): {
      return: {
       selectedImage: "@/assets/images/pics/cover_info.jpeg", // This can be changed
      }
     },
     computed: {
      imageUrl() {
       return new URL(`{selectedImage}`, import.meta.url).href;
      }
     }
    };
    </script>
    
    Login or Signup to reply.
  2. You need import a img in vue3 and vite

    //child.vue
    <template>
      <img :src="src">
    </template>
    <script>
    export default {
      name: 'Image',
      props:{
      src:{}
      }
    }
    };
    </script>
    
    //parent.vue
    <template>
      <child :src="ImgUrl">
    </template>
    <script>
    import ImgUrl from '@/assets/images/pics/cover_info.jpeg'
    export default {
      name: 'Image',
      data() {
      return {
        ImgUrl
      };
    }
    };
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search