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
```
4
  • did you try <img class="center" :src="require(test.imageSrcLocalFolder)" alt="image" />? Commented Apr 7, 2020 at 11:48
  • @BoussadjraBrahim Error in runtime: Error in render: "Error: Cannot find module './a1-1.png'" Commented Apr 7, 2020 at 12:05
  • you should respect the relative path Commented Apr 7, 2020 at 12:08
  • @BoussadjraBrahim Thanks! Commented Apr 7, 2020 at 12:41

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, using private test = { imageSrc: require('../assets/a1-1.png') } worked!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.