mx_code
mx_code

Reputation: 2527

How to dynamically bind to :src of img in vue js?

Following is the code for binding to src attribute of img tag. I'm being able to bind to the attribute. But the link is not getting the real icon from assets folder, instead shows a 404 or not found.

  <router-link
    v-for="nav in navigations"
    :to="'/' + nav"
  >
    <img
      class="icon"
      :src="'@/assets/icons/'+nav+'.svg'"
    />
    {{navigation}}
  </router-link>

Real question : How can I dynamically bind to an attribute with a variable between string i.e. '@/assets/icons/' + nav + '.svg' ? like this?

When I inspect the element it is showing the same path. ie @/assets/icons/{{iconnamehere}}.svg But the real icon is not showing up.

But if I do something like this without any binding <img src="@/assets/icons/logo.svg" />

then the image shows... When I inspect the element I see a replaced path something like this `

Upvotes: 3

Views: 1255

Answers (1)

overlox
overlox

Reputation: 822

Hope you have figured this out by now, but turns out you have to do the following :

  methods: {
    getPic (name) {
      return require("@/assets/icons/"+name+".svg")
    }
  }
    <img
      class="icon"
      :src="getPic(nav)"
    />

Upvotes: 1

Related Questions