vue中動態(tài)修改img標簽中src的方法實踐
首先看vue中img標簽的常規(guī)寫法
<img src="@/assets/images/xxx.png" alt="">
當src需要動態(tài)修改時,有點麻煩,經常忘記,記錄一下
vue2解決方案
<template> <div> <img :src="imgsrc" alt=""> </div> </template> export default { data(){ return { imgsrc: require('../../assets/images/user.png') } } }
可以通過相關的方法改變this.imgsrc的值,實現動態(tài)修改src的值
vue3解決方案
發(fā)現vue3+vite不能使用require,一使用就報錯,找了半天,找了個解決方案
實際情況:通過心知天氣返回的天氣code獲取對應的天氣圖標
獲取相關的接口就不寫了,直接寫相關的代碼
需要先寫一個轉換URL的方法
const getImgUrl = code => { return new URL(`../../../assets/weather/$[code].png`, import.meta.url).href }
code就是從心知天氣返回的天氣代碼,對應的圖片我放在src/assets/weather/文件夾下,code值+.png對應相關的天氣圖片
完整使用
<script setup> import { ref, onMounted } from 'vue' // 獲取天氣相關 import axios from 'axios' const imgsrc = ref('') // vue3+vite不能直接使用require動態(tài)修改img的src,試試下面這種方式 const getImgUrl = code => { ? ? return new URL(`../../../assets/weather/$[code].png`, import.meta.url).href } const getWeather = async () => { ? ? const url = 'https://api.seniverse.com/v3/weather/now.json?key=yourkey&location=wuxi&language=zh-Hans&unit=c' ? ? const {data, error} = await axios.get(url) ? ? // console.log(data) ? ? const result = data.results[0].now ? ? // console.log(result) ? ? imgsrc.value = getImgUrl(result.code) } onMounted(() => { ? ? getWeather() }) </script> <template> ? ? <nav class="app-topnav"> ? ? ? ? <div class="weather"> ? ? ? ? ? ? <img :src="imgsrc" alt=""> ? ? ? ? </div> ? ? </nav> </template> <style scoped lang="scss"> </style>
僅保留相關的代碼,經測,可用
到此這篇關于vue中動態(tài)修改img標簽中src的方法實踐的文章就介紹到這了,更多相關vue 動態(tài)修改img src內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue element插件this.$confirm用法及說明(取消也可以發(fā)請求)
這篇文章主要介紹了vue element插件this.$confirm用法及說明(取消也可以發(fā)請求),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10