vite项目静态资源处理
在vite创建的项目中,如果要在定义的变量里引入静态资源(例如图片),不能用require(require是webpack离的),可以将资源引入为 URL
下面是使用例子:
vue
<template>
<van-tabbar v-model="activeRef">
<van-tabbar-item
v-for="(item, index) in tabbarItemList"
:key="index"
replace
:name="item.name"
:to="item.to"
>
<span>{{item.text}}</span>
<template #icon="props">
<img :src="props.active ? getImageUrl(item.active) : getImageUrl(item.inactive)" />
</template>
</van-tabbar-item>
</van-tabbar>
</template>
<script setup>
import { watch } from 'vue'
const props = defineProps({
active: {
type: String,
default: 'home'
}
})
const activeVal = ref('home')
watch(() => props.active, (newVal) => {
activeVal.value = newVal
}, {
immediate: true
})
const tabbarItemList = [
{
text: '首页',
name: 'home',
to: '/home',
active: 'icon_home_sel.png',
inactive: 'icon_home_nor.png'
},
{
text: '院内就诊',
name: 'hospitalvisit',
to: '/hospitalvisit',
active: 'icon_hospitalvisit_sel.png',
inactive: 'icon_hospitalvisit_nor.png'
},
{
text: '资讯',
name: 'news',
to: '/news',
active: 'icon_news_sel.png',
inactive: 'icon_news_nor.png'
},
{
text: '我的',
name: 'my',
to: '/my',
active: 'icon_my_sel.png',
inactive: 'icon_my_nor.png'
}
]
// 动态获取图片的url
const getImageUrl = (name) => {
return new URL(`./${name}`, import.meta.url).href
}
</script>
使用方法:
1、active/inactive赋值图片名称
2、新建动态获取图片的url方法
3、在循环里,调用动态获取图片的url方法
备注
new URL(url, import.meta.url),import.meta.url 是一个 ESM 的原生功能,会暴露当前模块的 URL。