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粉3203612012023-12-30 12:27:15
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.
<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
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 })