Appearance
静态引入图片
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', i |
动态引入 | 不支持直接动态 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;
}