Heim  >  Fragen und Antworten  >  Hauptteil

So verwenden Sie eine Variable als Bildquelle – vue.js

Ich bin neu bei Vue und beschäftige mich mit HTML und CSS. Ich möchte eine Variable für das Bildverzeichnis verwenden, aber die Bilder werden nie geladen und die Variable wird von einer gültigen Tauri-Funktion aktualisiert, und ich muss die Bilder ebenfalls ändern.

Das ist ein Teil meines Codes

<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粉148434742P粉148434742295 Tage vor515

Antworte allen(1)Ich werde antworten

  • P粉320361201

    P粉3203612012023-12-30 12:27:15

    根据您的代码,您正在使用 Vue3 Composition API。您的代码中缺少一些内容,这些内容可能无法让您的应用正常运行。

    1. 正如其他人提到的,您不在属性中使用花括号。您使用
    <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. 当您使用组合API时,您必须先导入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>
    

    额外:当处理不需要参数的值时,通常使用计算会更好。请参阅 Vue 计算属性

    <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
    })
    

    Antwort
    0
  • StornierenAntwort