How to use variable as image src - vue.js
P粉148434742
P粉148434742 2023-12-29 16:42:56
0
1
564

I'm new to Vue and doing some html and css and I want to use a variable as the image directory but the images never load and the variable is being updated by a valid tauri function and I need the images to change as well.

This is some 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>

P粉148434742
P粉148434742

reply all(1)
P粉320361201

According to your code, you are using Vue3 Composition API. There's something missing in your code that might not make your app work properly.

  1. As others have mentioned, you don't use curly braces in attributes. You use
<img :src="variable"> // just use : in front of an attribute and it will consider as v-bind
<img v-bind:src="variable"> // or you directly use v-bind, less commonly used
<img :src="'static string'"> // no point doing this, but just a reference of how it works
  1. When you use the composition API, you must first import functions such as ref.
<template>
  <img :src="data">
  <img v-bind:src="data">
  <img :src="getimg()">
</template>

<script setup>
import { ref } from 'vue'

const data = ref("./assets/4168-376.png") // prefer const over var cus this variable will never be reassigned

function getimg() {
   // why are you using data1.value tho? It should be data.value
   // also i don't think 'require' is needed here 
   return require(data1.value) // i just copy paste from your code
}
</script>

Extra: When dealing with values ​​that don't require arguments, it's often better to use computation. See Vue Computed Properties

<template>
   <img :src="data">
   <img v-bind:src="data">
   <img :src="getImg">
</template>

<script setup>
import { ref, computed } from 'vue' // import it first

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

const getImg = computed(() => {
  return data.value
})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template