1

I have been looking at the following question but I can't get images to load correctly when setting src from an object.

How can I use 'img src' in Vue.js?

I created a new Vue project with TypeScript using the following guide:

https://v2.vuejs.org/v2/guide/typescript.html

  1. Install Vue CLI, if it's not already installed

    npm install --global @vue/cli

  2. Create a new project, then choose the "Manually select features" option

    vue create my-project-name

I choose to add every feature for this project:

enter image description here

When running this code I can see an image for the hard coded src but not the dynamic :src loaded from an object. Could this be due to Babel or CSS-Pre-processor? I choose to use Sass/SCSS (with dart-sass) as a CSS-Pre-processor.

<template>
    <div>
        <img class="center" :src="test.imageSrc" alt="image" />
        <img class="center" :src="test.imageSrcLocalFolder" alt="image" />
        <img class="center" src="./a1-1.png" alt="image" />
        <img class="center" src="../assets/a1-1.png" alt="image" />
    </div>
</template>

<script lang="ts">
    import { Component, Vue } from 'vue-property-decorator';

    @Component
    export default class HelloWorld extends Vue {
        private test = {
            imageSrc: '../assets/a1-1.png',
            imageSrcLocalFolder: './a1-1.png',
        }

    }
</script>

Inspecting elements look like this:

enter image description here

I start the dev server running npm run serve as described in the README.md file and in the documentation. This calls the script vue-cli-service serve from package.json.

https://cli.vuejs.org/guide/cli-service.html

README.md:

### Compiles and hot-reloads for development
```
npm run serve
```
tony19
  • 125,647
  • 18
  • 229
  • 307
Ogglas
  • 62,132
  • 37
  • 328
  • 418

1 Answers1

2

When you want to use an asset you need to use require so the path gets resolved to a runtime accessible path.

When you are adding the src in the template part it get's parsed and in the end it will be wrapped around an require.

You need to add require to your path.

Radu Diță
  • 13,476
  • 2
  • 30
  • 34