vue3 + vite动态引入图片以及本地正常展示,线上部署不正常显示的解决方法

方案一 使用import引入

import imgUrl from './img.png'
document.getElementById('hero-img').src = imgUrl

方案二 使用 new URL

// ../assets/imgs为图片公共路径
export function getAssetsFile(url: string) {
  return new URL(`../assets/imgs/${url}`, import.meta.url).href;
};
// 这种写法打包部署到服务器后,图片加载不出来
export function getAssetsFile(url: string) {
  return new URL(url, import.meta.url).href;
};

vite官方描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
动态加载路由可以使用 Vue Router 提供的 `async` 函数来实现。在 Vue Router 中,我们可以通过 `routes` 配置项来配置路由,而 `routes` 可以是一个数组,也可以是一个返回数组的函数。这个函数可以异步加载路由配置,比如从服务器获取路由配置信息。 下面是一个简单的例子: ```javascript const router = createRouter({ routes: [ { path: '/', name: 'Home', component: () => import('@/views/Home.vue') }, { path: '/about', name: 'About', component: () => import('@/views/About.vue') }, { path: '/dynamic', name: 'Dynamic', component: () => import('@/views/Dynamic.vue') }, // ... ] }) ``` 在这个例子中,我们使用 `import()` 函数来异步加载组件。当用户访问 `/dynamic` 路径时,这个组件才会被动态加载。 为了本地路由和线上路由匹配,我们可以使用环境变量来判断当前是否处于线上环境。比如我们可以在 `.env` 文件中定义一个环境变量 `VUE_APP_ENV`: ```env VUE_APP_ENV=production ``` 然后在代码中使用 `process.env.VUE_APP_ENV` 来获取当前环境变量的值。根据不同的值,我们可以加载不同的路由配置。 下面是一个示例代码: ```javascript const routes = [ { path: '/', name: 'Home', component: () => import('@/views/Home.vue') }, { path: '/about', name: 'About', component: () => import('@/views/About.vue') }, // ... ] if (process.env.VUE_APP_ENV === 'production') { // 在线上环境加载动态路由 import('@/router/routes.production').then(routes => { router.addRoutes(routes.default) }) } else { // 在本地环境直接使用静态路由 router.addRoutes(routes) } ``` 在上面的代码中,我们先定义了一个静态的路由配置 `routes`,然后根据环境变量的值来加载不同的路由配置。在线上环境下,我们使用 `import()` 函数异步加载一个 `routes.production.js` 文件,该文件返回一个路由配置数组;在本地环境下,我们直接使用静态路由配置。最后使用 `router.addRoutes()` 函数将动态路由添加到路由中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值