0

I want to generate some v-chip objects with variable names and images. The source string of the image depends on the name. When I bind the name to the source string the image doesn't load. I already read a similar question with a solution (Vue.js img src concatenate variable and text) but it just doesn't work for me.

I tried two different ways as you can see in the code. One with binding a props and one with a computed function. Both not working.

<template>    
<div>
    <v-chip v-model="perso">
        <v-avatar>
          <img :src="'../assets/' + perso_name + '.png'"> <!--Doesn't work-->
        </v-avatar>
        {{perso_name}}
    </v-chip>   
    <v-chip v-model="perso">
        <v-avatar>
          <img :src="'../assets/' + foo + '.png'"> <!--Doesn't work-->
        </v-avatar>
        {{perso_name}}
    </v-chip>
    <v-chip v-model="perso">
        <v-avatar>
          <img src="../assets/Jon.png"> <!--This works-->
        </v-avatar>
        {{perso_name}}
    </v-chip>
</div>
</template>

<script>
export default {
  data () {
      return { perso: true }
  },
  name: 'Personal',
  props: ['perso_name'],
  computed: {
    foo: function() {
      return this.perso_name;
    }
  }
}
</script>

I don't get an error but the image isn't loading. It just shows the broken file icon.

SunnySide
  • 89
  • 6

2 Answers2

2

You can use template strings. Surround the attribute value with '``' and the variable with ${}

<img :src="`../assets/${perso_name}.png`">
gpasci
  • 1,420
  • 11
  • 16
0

in your question you didn't show your rendered img src of your broken file icon.So i can only speculate the problem is the file path in your server is incorrect.

The src attr is very special,some packing tool(like webpack) use this attr to locate your img,and transform/repalce it with the right path when you packing your project.

In your case,you bind the src attr with vue binding,and the path looks like a relative path from the img file to your .vue file. It's easy to go wrong because the browser load the img from the root path of your website.

i suggest you trying like this:

  • use webpack import to save your packaged img path to a dictionary

<script>

var urlDic ={};
urlDic.Jon = require('../assets/Jon.jpg');
urlDic.Mike = require('../assets/Mike.jpg');

export default {
  data () {
      return { 
         urls: urlDic //save the dic to your data
       }
  },
  name: 'Personal',
  props: ['perso_name']
}
</script>

  • the bind the img src to the preloaded img paths
     <v-chip v-model="perso">
        <v-avatar>
          <img :src="urls[perso_name]"> <!--it will work-->
        </v-avatar>
        {{perso_name}}
    </v-chip>   
Kaicui
  • 3,795
  • 1
  • 15
  • 20