简体   繁体   中英

Dynamically change src path in vuejs

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>

图片未加载

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.

For dynamic URLs, use require() :

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

demo

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM