SoFunction
Updated on 2025-04-05

Practice of method of dynamically modifying src in img tag in vue

First, look at the general writing method of img tag in vue

<img src="@/assets/images/" alt="">

When src needs dynamic modification, it is a bit troublesome. I often forget it and record it.

vue2 solution

<template>
    <div>
        <img :src="imgsrc" alt="">
    </div>
</template>
export default {
    data(){
        return {
            imgsrc: require('../../assets/images/')
        }
    }
}

The value of src can be changed through related methods to dynamically modify the value of src.

vue3 solution

I found that vue3+vite cannot use require, and it reported an error as soon as it is used. I searched for a long time and found a solution.

Actual situation: Get the corresponding weather icon by knowing the weather code returned by the weather

If you get the relevant interface, don't write it, just write the relevant code.

You need to write a method to convert the URL first

const getImgUrl = code => {
    return new URL(`../../../assets/weather/$[code].png`, ).href
}

code is the weather code returned from the Xinzhi weather. I put the corresponding image in the src/assets/weather/ folder, and the code value +.png corresponds to the relevant weather pictures.

Complete use

&lt;script setup&gt;
import { ref, onMounted } from 'vue'
// Get weather relatedimport axios from 'axios'
const imgsrc = ref('')
// vue3+vite cannot use require to dynamically modify img's src directly. Try the following methodconst getImgUrl = code =&gt; {
    return new URL(`../../../assets/weather/$[code].png`, ).href
}
const getWeather = async () =&gt; {
    const url = '/v3/weather/?key=yourkey&amp;location=wuxi&amp;language=zh-Hans&amp;unit=c'
    const {data, error} = await (url)
    // (data)
    const result = [0].now
    // (result)
     = getImgUrl()
}
onMounted(() =&gt; {
    getWeather()
})
&lt;/script&gt;
&lt;template&gt;
    &lt;nav class="app-topnav"&gt;
        &lt;div class="weather"&gt;
            &lt;img :src="imgsrc" alt=""&gt;
        &lt;/div&gt;
    &lt;/nav&gt;
&lt;/template&gt;
&lt;style scoped lang="scss"&gt;
&lt;/style&gt;

Only relevant codes are retained, tested and available

This is the article about the practice of dynamically modifying src in the img tag in vue. This is the end. For more related vue dynamically modifying img src content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!