Skip to content

静态引入图片

TIP

从 Vue2 到 Vue3,图片引入方式有了大变化

Vue3 推荐方式:使用import.meta.url

js
// 方法一:封装函数动态生成URL
const getImgSrc = (path) => {
  return new URL(path, import.meta.url).href;
}

// 在模板中使用
<template>
  <img :src="getImgSrc('../assets/images/user.png')" alt="用户头像">
</template>
// 方法一:封装函数动态生成URL
const getImgSrc = (path) => {
  return new URL(path, import.meta.url).href;
}

// 在模板中使用
<template>
  <img :src="getImgSrc('../assets/images/user.png')" alt="用户头像">
</template>

Vue3 与 Vue2 引入方式对比

场景Vue2 方式Vue3 推荐方式
静态引入require('../assets/img.png')new URL('./img.png', import.meta.url).href
动态引入不支持直接动态 require支持动态路径拼接(见下文)
组件中使用需要先 import 再使用直接在模板中生成 URL
类型支持无类型检查支持 TypeScript 类型推导

vue2正常使用

js
const imgSrc = require("../assets/images/user.png");
const imgSrc = require("../assets/images/user.png");

vue3正常使用

js
const getImgSrc = ()=>{
	return new URL("../assets/images/user.png",import.meta.url).href;
}
const getImgSrc = ()=>{
	return new URL("../assets/images/user.png",import.meta.url).href;
}

程序员小洛文档