美文网首页
uniapp+Vue3+Vite 实现动态访问静态图片(含微信小

uniapp+Vue3+Vite 实现动态访问静态图片(含微信小

作者: 我是七月 | 来源:发表于2024-03-12 09:16 被阅读0次
前言:在最近新起的项目中,用到了较新uniapp+vue3.2+vite,Vite的特性和 webpack 不一样 ,所以require 将不能使用 。
<img :src="require('@/static/images/home/home_bg.png')" />

通过require动态引入, 发现报错:require is not defind,这是因为 require 是属于 Webpack 的方法

第一种方式(适用于单个资源文件)

import homeBg from '/src/static/images/home/home_bg.png'

<img :src="homeBg" />

第二种方式(适用于多个资源文件,动态传入文件路径,不适用小程序端)

new URL() + import.meta.url

import { computed } from 'vue'
 
<img :src="getAssetsImages('home_bg')" />
 
let getAssetsImages = computed(() => (name, type = 'png') => {
    return new URL(`/static/images/home/${name}.${type}`, import.meta.url).href; //h5用法
})

在微信小程序端调试了一下,因为new url相当于window.location.href,以至于小程序里是无法使用的~~~~

第三种方式(适用于多个资源文件,这种方式引入的文件必须指定到具体文件夹路径,传入的变量中只能为文件名,不能包含文件路径,h5和微信小程序均适用)

import { computed } from 'vue'
 
<img :src="getAssetsImages('home_bg','jpg')" />
 
let getAssetsImages = computed(() => (name, type = 'png') => {
    /**
     * 获取本地图
     * @param name // 文件名 如 home-bg
     * @param type // 文件类型 如 png jpg
     * @returns {*|string}
     */
    const path = `/src/static/images/home/${name}.${type}`
    const modules = import.meta.globEager('/src/static/images/home/*')
    return modules[path].default
})

/*import.meta.glob

  • 该方法匹配到的文件默认是懒加载,通过动态导入实现,构建时会分离独立的 chunk,
    是异步导入,返回的是 Promise
  • /*import.meta.globEager
  • 该方法是直接导入所有模块,并且是同步导入,返回结果直接通过 for...in循环就可以操作*

使用background-image背景图属性引入

1.官方文档说:支持 dase64 格式图片。 支持网络路径图片。40kb以下小图片推荐使用以 ~@ 开头的绝对路径;大图片推荐使用网络地址 。微信小程序不支持相对路径(真机不支持,开发工具支持)

/* 推荐~@绝对路径引入 */
background-image: url("~@/static/images/home/home_bg.png");

相关文章

网友评论

      本文标题:uniapp+Vue3+Vite 实现动态访问静态图片(含微信小

      本文链接:https://www.haomeiwen.com/subject/luuvzdtx.html