vue中動(dòng)態(tài)修改img標(biāo)簽中src的方法實(shí)踐
首先看vue中img標(biāo)簽的常規(guī)寫法
<img src="@/assets/images/xxx.png" alt="">
當(dāng)src需要?jiǎng)討B(tài)修改時(shí),有點(diǎn)麻煩,經(jīng)常忘記,記錄一下
vue2解決方案
<template> <div> <img :src="imgsrc" alt=""> </div> </template> export default { data(){ return { imgsrc: require('../../assets/images/user.png') } } }
可以通過相關(guān)的方法改變this.imgsrc的值,實(shí)現(xiàn)動(dòng)態(tài)修改src的值
vue3解決方案
發(fā)現(xiàn)vue3+vite不能使用require,一使用就報(bào)錯(cuò),找了半天,找了個(gè)解決方案
實(shí)際情況:通過心知天氣返回的天氣code獲取對(duì)應(yīng)的天氣圖標(biāo)
獲取相關(guān)的接口就不寫了,直接寫相關(guān)的代碼
需要先寫一個(gè)轉(zhuǎn)換URL的方法
const getImgUrl = code => { return new URL(`../../../assets/weather/$[code].png`, import.meta.url).href }
code就是從心知天氣返回的天氣代碼,對(duì)應(yīng)的圖片我放在src/assets/weather/文件夾下,code值+.png對(duì)應(yīng)相關(guān)的天氣圖片
完整使用
<script setup> import { ref, onMounted } from 'vue' // 獲取天氣相關(guān) import axios from 'axios' const imgsrc = ref('') // vue3+vite不能直接使用require動(dòng)態(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>
僅保留相關(guān)的代碼,經(jīng)測(cè),可用
到此這篇關(guān)于vue中動(dòng)態(tài)修改img標(biāo)簽中src的方法實(shí)踐的文章就介紹到這了,更多相關(guān)vue 動(dòng)態(tài)修改img src內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue element插件this.$confirm用法及說明(取消也可以發(fā)請(qǐng)求)
這篇文章主要介紹了vue element插件this.$confirm用法及說明(取消也可以發(fā)請(qǐng)求),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10Vue v-model相關(guān)知識(shí)總結(jié)
這篇文章主要介紹了Vue ​v-model相關(guān)知識(shí)總結(jié),幫助大家更好的理解和學(xué)習(xí)使用vue框架,感興趣的朋友可以了解下2021-01-01Vue項(xiàng)目部署到j(luò)enkins的實(shí)現(xiàn)
本文主要介紹了Vue項(xiàng)目部署到j(luò)enkins的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02vue-cli 為項(xiàng)目設(shè)置別名的方法
這篇文章主要介紹了vue-cli 為項(xiàng)目設(shè)置別名的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10VUE實(shí)現(xiàn)自動(dòng)滾動(dòng)簡單示例
這篇文章主要給大家介紹了關(guān)于VUE實(shí)現(xiàn)自動(dòng)滾動(dòng)的相關(guān)資料,現(xiàn)在很多數(shù)據(jù)展示大屏都會(huì)有很多的自動(dòng)滾動(dòng)的列表,文中通過代碼實(shí)例介紹的非常詳細(xì),需要的朋友可以參考下2023-08-08如何在 ant 的table中實(shí)現(xiàn)圖片的渲染操作
這篇文章主要介紹了如何在 ant 的table中實(shí)現(xiàn)圖片的渲染操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-10-10