1
votes

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

How to use img src in vue.js?

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

https://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
```
1
did you try <img class="center" :src="require(test.imageSrcLocalFolder)" alt="image" />?Boussadjra Brahim
@BoussadjraBrahim Error in runtime: Error in render: "Error: Cannot find module './a1-1.png'"Ogglas
you should respect the relative pathBoussadjra Brahim
@BoussadjraBrahim Thanks!Ogglas

1 Answers

2
votes

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.