vue3+vite2實(shí)現(xiàn)動(dòng)態(tài)綁定圖片的優(yōu)雅解決方案
背景
在vue3+vite2項(xiàng)目中,我們有時(shí)候想要?jiǎng)討B(tài)綁定資源,比如像下面的代碼這樣:
<template>
<div>
<!-- 動(dòng)態(tài)綁定圖片資源 -->
<img :src="img_src">
</div>
</template>
<script setup>
import { ref } from 'vue';
// 靜態(tài)圖片資源
const img_src = ref('./1.jpg');
</script>實(shí)際效果是這樣:

原因分析
我們注意到,控制臺(tái)的報(bào)錯(cuò)信息GET http://127.0.0.1:5173/1.jpg 404 (Not Found)
GET:表示向服務(wù)器請(qǐng)求資源的方式。http://127.0.0.1:5173:表示主機(jī)為項(xiàng)目開啟的服務(wù)器地址以及端口號(hào)http://127.0.0.1:5173/1.jpg:表示存放在服務(wù)器中的圖片資源地址。404 (Not Found):狀態(tài)碼,404表示找不到資源。
問題就出在http://127.0.0.1:5173/1.jpg 這里,項(xiàng)目文件的路徑是src/App.vue ,圖片的路徑是src/1.jpg ,因此,圖片在服務(wù)器上的存放路徑實(shí)際應(yīng)該是http://127.0.0.1:5173/src/1.jpg ,我們直接在瀏覽器中訪問這個(gè)地址。

可以看到,成功獲取了圖片資源。
由于vite打包的機(jī)制,造成了路徑錯(cuò)誤的問題(類似于vue2 + vue-cli項(xiàng)目的動(dòng)態(tài)綁定圖片問題)。
解決
目前網(wǎng)上的解決方案有很多,這里列出其中一種受眾的,以及筆者在此基礎(chǔ)上進(jìn)一步加強(qiáng)的解決方案。
普遍的解決方案
話不多說(shuō),直接列出代碼:
<template>
<div>
<!-- 動(dòng)態(tài)綁定圖片資源 -->
<img :src="img_src">
</div>
</template>
<script setup>
import { ref } from 'vue';
// 靜態(tài)圖片資源
const img_src = ref('./1.jpg');
// 主要代碼,利用 new URL().href 進(jìn)行相對(duì)路徑的拼接
function getAssetImage(imgSrc) {
return new URL(imgSrc, import.meta.url).href;
}
// 當(dāng)然你也可以這樣簡(jiǎn)寫,這里用到es6箭頭函數(shù)
// const getAssetImage = imgSrc => new URL(imgSrc, import.meta.url).href;
</script>這段代碼的重點(diǎn)是new URL().href 和 es6的 import.meta.url 。
new URL(url, baseUrl).href:路徑拼接。比如url是./1.jpg,baseUrl是http://127.0.0.1:5173/src/App.vue,那么拼接出來(lái)就是http://127.0.0.1:5173/src/1.jpgimport.meta.url:獲取當(dāng)前模塊的路徑,比如在src/App.vue中,就是http://127.0.0.1:5173/src/App.vue。
所以最后的new URL().href 就是真正的圖片資源地址,自己打印一下new URL(url, baseUrl) 和import.meta.url 就容易明白了。
這里給大伙兒畫張圖,便于理解。

優(yōu)雅的解決方案
上面的方案可行,但不夠優(yōu)雅。試想,如果有很多文件都需要?jiǎng)討B(tài)綁定靜態(tài)圖片資源,那豈不是每個(gè).vue文件都要封裝一次getAssetImage() 函數(shù)?所以下面介紹一種優(yōu)雅的封裝方案。
封裝的主要問題是如何自動(dòng)獲取.vue文件的import.meta.url ,就可以不必每次調(diào)用都攜帶import.meta.url。
核心思路是通過拋出錯(cuò)誤獲取函數(shù)調(diào)用棧,從而獲得函數(shù)調(diào)用者文件(或者說(shuō)模塊)的路徑,再通過正則表達(dá)式提取出路徑信息,把import.meta.url替換掉,就能實(shí)現(xiàn),只傳圖片相對(duì)路徑這一個(gè)參數(shù),得到圖片的完整路徑的效果。
直接上代碼:
JavaScript版本
// src/utils/common.js
export default {
getAssetImage(imgSrc, baseUrl) {
// console.log('baseUrl', baseUrl);
// console.log('new URL(imgSrc, baseUrl).href', new URL(imgSrc, baseUrl).href);
// console.log('import.meta.url', import.meta.url);
// console.log('new URL(imgSrc, import.meta.url).href', new URL(imgSrc, import.meta.url).href);
// 正則匹配函數(shù)調(diào)用者文件的路徑
const regExp1 = /at Proxy.getAssetImage \((.+)\)/g;
// 正則命中目標(biāo)
let target;
try {
// 拋出錯(cuò)誤,獲取函數(shù)調(diào)用棧信息
throw new Error();
} catch (err) {
// 匹配函數(shù)調(diào)用者文件的路徑
target = regExp1.exec(err?.stack);
// console.log('err.stack', err?.stack);
// console.log(target?.[1]);
}
if (target?.[1]) {
// 用戶沒有傳入第二個(gè)參數(shù),就使用自動(dòng)獲取的路徑
baseUrl = baseUrl || target?.[1];
}
if (!baseUrl) {
// 用戶沒有傳入第二個(gè)參數(shù),且獲取函數(shù)調(diào)用者文件的路徑失敗
throw new Error('請(qǐng)傳入第二個(gè)參數(shù) import.meta.url');
}
// 返回處理后的資源路徑
return new URL(imgSrc, baseUrl).href;
}
}TypeScript版本
// src/utils/common.ts
export default {
getAssetImage(imgSrc: string, baseUrl: string) {
// console.log('baseUrl', baseUrl);
// console.log('new URL(imgSrc, baseUrl).href', new URL(imgSrc, baseUrl).href);
// console.log('import.meta.url', import.meta.url);
// console.log('new URL(imgSrc, import.meta.url).href', new URL(imgSrc, import.meta.url).href);
// 正則匹配函數(shù)調(diào)用者文件的路徑
const regExp1 = /at Proxy.getAssetImage \((.+)\)/g;
// 正則命中目標(biāo)
let target: RegExpExecArray | null;
try {
// 拋出錯(cuò)誤,獲取函數(shù)調(diào)用棧信息
throw new Error();
} catch (err) {
// 匹配函數(shù)調(diào)用者文件的路徑
target = regExp1.exec(err?.stack);
// console.log('err.stack', err?.stack);
// console.log(target?.[1]);
}
if (target?.[1]) {
// 用戶沒有傳入第二個(gè)參數(shù),就使用自動(dòng)獲取的路徑
baseUrl = baseUrl || target?.[1];
}
if (!baseUrl) {
// 用戶沒有傳入第二個(gè)參數(shù),且獲取函數(shù)調(diào)用者文件的路徑失敗
throw new Error('請(qǐng)傳入第二個(gè)參數(shù) import.meta.url');
}
// 返回處理后的資源路徑
return new URL(imgSrc, baseUrl).href;
}
}在.vue文件中使用
// src/App.vue
<template>
<div>
<!-- 測(cè)試 -->
<img :src="getAssetImage(img_src)">
<!-- 可以試試在嵌套組件中使用^_^ -->
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import common from '@/utils/common.ts';
const img_src = ref('./1.jpg');
// const getAssetImage = img_src => common.getAssetImage(img_src, import.meta.url);
// 可以省略第二個(gè)參數(shù)import.meta.url,函數(shù)內(nèi)部會(huì)自動(dòng)獲取函數(shù)的調(diào)用路徑。
const getAssetImage = img_src => common.getAssetImage(img_src);
// 常規(guī)寫法
// function getAssetImage(img_src) {
// return common.getAssetImage(img_src);
// }
</script>到此這篇關(guān)于vue3+vite2實(shí)現(xiàn)動(dòng)態(tài)綁定圖片的優(yōu)雅解決方案的文章就介紹到這了,更多相關(guān)vue3 vite2動(dòng)態(tài)綁定圖片內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue2利用Bus.js如何實(shí)現(xiàn)非父子組件通信詳解
這篇文章主要給大家介紹了關(guān)于vue2利用Bus.js如何實(shí)現(xiàn)非父子組件通信的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-08-08
vue如何使用element-ui 實(shí)現(xiàn)自定義分頁(yè)
這篇文章主要介紹了vue如何使用element-ui 實(shí)現(xiàn)自定義分頁(yè),可以通過插槽實(shí)現(xiàn)自定義的分頁(yè),本文通過實(shí)例圖文相結(jié)合給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2024-07-07
vue模塊導(dǎo)入報(bào)錯(cuò)問題Module not found: Error:[CaseSensi
這篇文章主要介紹了vue模塊導(dǎo)入報(bào)錯(cuò)問題Module not found: Error:[CaseSensitivePathsPlugin],具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
vue-editor-bridge報(bào)錯(cuò)的解決方案
這篇文章主要介紹了vue-editor-bridge報(bào)錯(cuò)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04

