獲取國家對應的國旗圖片(Vite 方式)
在 Vue.js 項目中,若你需要根據國家名稱動態(tài)加載國旗圖片,可以結合 Vite 的靜態(tài)資源處理功能來實現這一需求。下面是一個實現方案。
1. 模板部分
首先,我們需要在模板中顯示國旗圖片。假設我們有一個 demands 數組,每個對象中包含一個 countryDelivery 屬性,表示國家名稱。我們將通過 getCountryFlag 方法動態(tài)獲取對應的國旗圖片路徑。
<div
class="demand-card"
v-for="(demand, index) in demands"
:key="index"
>
<div class="demand-item flex">
<div class="country flex align-center" >
<img :src="getCountryFlag(demand.countryDelivery)" alt="">
</div>
</div>
2. JavaScript 部分
getCountryFlag 方法負責接收國家名稱并返回對應的圖片路徑。在 Vite 中,我們可以使用 import.meta.url 來確保正確地處理相對路徑。這里的邏輯是根據國家名稱拼接出圖片路徑,如果找不到對應的圖片,我們可以返回默認的國旗圖片。
demand.countryDelivery 是國家名字,現在assest里有國家圖片,國家圖片和返回國家名字一致,
const getCountryFlag = (countryName) => {
const countryCode = countryName.toLowerCase(); // 可選:轉小寫以統(tǒng)一命名規(guī)則
try {
// 構建動態(tài)路徑,加載對應國家的國旗圖片
return new URL(`../../../assets/image/${countryCode}.png`, import.meta.url).href;
} catch (e) {
// 如果找不到圖片,返回默認的國旗圖片
return new URL(`../../assets/image/default.png`, import.meta.url).href;
}
};