0

I want to dynamically change the path of my <img>'s src in Vue:

<template>
  <img :src="'../../assets/logo/'+LogoSrc()" alt="logo black" :height="height+'px'" />
</template>

<script>
export default {
  name: "Logo",
  props: {
    logoColor: {
      type: String,
      default: "dark"
    },
    height: {
      type: Number,
      default: 10
    }
  },
  data() {
    return {};
  },

  methods: {
    LogoSrc() {
      if (this.logoColor === "dark") {
        return "logo-black.svg";
      }
    }
  }
};
</script>

<style scoped>
</style>

image not loadng

Though the path is right, the image is still not loading. I tried using src without the v-bind with path being the same (../../assets/logo/logo-black.svg), and it seems to be working fine.

2 Answers 2

1

For dynamic URLs, use require():

<img :src="require('../../assets/logo/' + LogoSrc())">

demo

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

Comments

0

Make it a computed value:

<template>
  <img :src="LogoSrc" alt="logo black" :height="height+'px'" />
</template>

<script>
export default {
  name: "Logo",
  props: {
    logoColor: {
      type: String,
      default: "dark"
    },
    height: {
      type: Number,
      default: 10
    }
  },
  data() {
    return {};
  },

  computed: {
    LogoSrc() {
      if (this.logoColor === "dark") 
        return "../../assets/logo/logo-black.svg";
      
      return "";
    }
  }
};
</script>

<style scoped>
</style>

Comments

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.