0

how do i load images in a assets folder to vue components?

This is my "Card.vue" component

<template>
  <div class="container">
    <div class="card" style="width: 18rem;">

     <!-- this <img> tag needs to load image from the assets folder -->
      <img :src="logo" class="card-img-top" alt="...">

      <div class="card-body">
        <h5 class="card-title">Card title</h5>
        <p class="card-text">Some quick example......</p>
    </div>
  </div>
</div>
</template>

This is the script of the "Card.vue" component

<script>
export default {
 data() {
     logo: require('@/assets/images/1.jpg')
}
}
</script>

I have tried in many ways to load images in an assets folder but its keep posting this same error every time.

Error code :

*ERROR in ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/components/card.vue
Module not found: Error: Can't resolve '@/assets/images/1.jpg'in 'e:\OTHERS\work\SIYASAWEB\siyasa-web-master\src\components'
 @ ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/components/card.vue 19:10-42
 @ ./src/components/card.vue
 @ ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue
 @ ./src/App.vue
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://localhost:8081 webpack/hot/dev-server ./src/main.js*

And this is the project tree structure

enter image description here

  • Have you tried relative paths? Here are some ways to do this: https://stackoverflow.com/questions/45116796/how-to-import-and-use-image-in-a-vue-single-file-component – DonTristras Nov 21 '19 at 17:12

1 Answers1

3

You need a loader that can handle images. url-loader works well compared to other loaders when utilizing babel-loader.

Adapted from the url-loader docs:

$ npm install url-loader --save-dev

Change the script tag of your Card.vue component:

<script>
import logo from '../assets/images/1.jpg';

export default {
    data() {
        return {
            logo
        }
    }
}
</script>

In the HTML of Card.vue:

<img :src="logo" class="card-img-top" alt="...">

Add the loader rule to your webpack.config.js:

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        use: [
          {
            loader: 'url-loader',
          },
        ],
      },
    ],
  },
};
Sterling Beason
  • 622
  • 6
  • 12