Home > Back-end >  How to use a variable as an image src - vue.js
How to use a variable as an image src - vue.js

Time:11-17

I'm new to Vue and done a little bit of html and css, i want to use a variable as the image directory but the image never loads, the variable is being updated by a tauri function which works and i need the image to change as well.

this is a bit of my code

<template>
<img v-bind:src=getimg()>

   -- and --

<img :src = {{data}}}>

   -- and --

<img src = {{data}}>

   -- and much more ... --

</template>

<script setup>

var data = ref("./assets/4168-376.png")

function getimg() {
    console.log(data1.value)
    return require(data1.value)
}

</setup>

Thanks in advance

CodePudding user response:

Try without curly braces:

<img :src="data">

CodePudding user response:

First, the syntax is:

v-bind:src /*or :src */

And not <img src = {{data}}>.

Next, the bind data should be part of the vue instance. Otherwise on binding you get an error.

Property or method 'getimg' is not defined on the instance but referenced during render.

Last, if you want to bind the value to a function you should run the function like this:

  <img :src="get_image()">
  <!-- Not   <img :src="get_image"> -->

Basic Snippet example (vue 2):

Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
  el: '#app',
  data: () => ({
    photo_path: "https://picsum.photos/id/237/111/111",
    
  }),
  methods: {
    get_image: function() {
      return "https://picsum.photos/id/237/111/111";
    },
  }
})

/* will not work */
function not_working(){
  return "https://picsum.photos/id/237/111/111";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<!-- Import Numeral.js (http://numeraljs.com/#use-it) -->
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.0/numeral.min.js"></script>
<!-- Then import vue-numerals -->
<script src="https://unpkg.com/vue-numerals/dist/vue-numerals.min.js"></script>

<div id="app">
  <img :src="photo_path">
  <img :src="get_image()">
  <img :src="not_working">  
</div>

v-bind docs:

  • Related