为了不在每个组件中重复编写路径处理逻辑,因此提取全局图片 URL 处理方法。
<div>
<img :src="$getImgSrc(url)" alt="" class="img" />
</div>
const url = '/upadte/demo.png'
如果已经是完整的 HTTP 或 HTTPS 链接,则直接使用;如果是相对路径,则自动添加配置的资源路径前缀。
* 获取完整的图片 URL(支持单个、逗号分隔字符串)
* @param url 图片路径(相对或绝对)
* @returns 完整的 URL 或 URL
*/
export function getImgSrc(url: string | null | undefined): string {
if (!url) return ''
const resourcesPath = '替换自己的图片地址域名'
// 处理字符串(逗号分隔)
const imgList = url.split(',').map((s) => s.trim()).filter(Boolean)
const result = imgList.map((item) => {
return item.startsWith('http://') || item.startsWith('https://')
? item
: resourcesPath + (item.startsWith('/') ? item : '/' + item)
})
return result.length === 1 ? result[0] : result.join(',')
}
如果接口返回的 URL 为数组格式,则可以添加以下代码
// 处理数组形式 (根据需要添加)
if (Array.isArray(url)) {
return url.map((item) => {
if (typeof item !== 'string') return item // 保持非字符串原样
return item.startsWith('http://') || item.startsWith('https://')
? item
: resourcesPath + (item.startsWith('/') ? item : '/' + item)
})
}
通过 app.config.globalProperties 将工具函数注册为全局方法,同时,为了更好的灵活性,建议将资源路径配置为环境变量,这样在不同部署环境中可以轻松切换。
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
import { getImgSrc } from '@/utils/index'
// 注册全局工具方法
app.config.globalProperties.$getImgSrc = getImgSrc
若出现 ts 报错:
Property '$getImgUrl' does not exist on type '{ $: ComponentInternalInstance; $data: {};
$props: Partial<{}> & Omit<{} & VNodeProps & AllowedComponentProps & ComponentCustomProps, never>; ... 11 more ...;
$watch<T extends string | ((...args: any) => any)>(source: T, cb:
T extends (...args: any) => infer R ? (args_0: R, args_1: R, args_2: OnCleanup) => any : (ar...'
这是因为 ts不知道在 app.config.globalProperties 上添加了 $getImgSrc 方法,所以模板或 .ts 文件中使用 $getImgSrc 时会报类型错误。
解决方案:创建后缀为 .d.ts 的文件,并确保 tsconfig.json 包含了该文件或目录(一般默认会扫描 src/types)
// @ts-ignore
import { getImgSrc } from '@/utils'
declare module 'vue' {
interface ComponentCustomProperties {
$getImgSrc: typeof getImgSrc
}
}