首頁  >  問答  >  主體

如何使用變數作為映像 src - vue.js

我是 Vue 新手,做了一些 html 和 css,我想使用一個變數作為圖像目錄,但圖像從未加載,該變數正在由一個有效的 tauri 函數更新,我需要圖像也會改變。

這是我的一些程式碼

<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 天前516

全部回覆(1)我來回復

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

    回覆
    0
  • 取消回覆