参考文章
Vue3+TS 解决 app.config.globalProperties 全局变量参数不存在问题 - 简书
实现
直接使用
new URL(`/src/assets/img/a.png`, import.meta.url).href
我们也可以定义一个全局的方法
let app = createApp(App);
app.config.globalProperties.$getImgSrc = (link: string) => {
return new URL(`/src/assets/img/${link}`, import.meta.url).href;
}
如果你使用了ts,直接在template中使用会报找不到这个方法需要在src下新建一个后缀为 .d.ts的文件内容如下:
// statement.d.ts
import { ComponentCustomProperties } from "@vue/runtime-core";
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
// 声明的每个全局变量或者方法都写在这里
$getImgSrc: Function; // 这里填类型
}
}
// 必须导出,才能在其他文件中使用
export default ComponentCustomProperties;
这样我们可以在template里面直接使用$getImgSrc方法,如果在script里面使用需要:
const {proxy} = getCurrentInstance()
console.log(proxy.$getImgSrc)