vue2:
webpack 创建的vue2可以通过 require对图片进行动态绑定
<script>
export default{data(){return{list:[{id:1,img:require("./assets/logo.png")},{id:2,img:require("./assets/logo.png")},{id:3,img:require("./assets/logo.png")}]}}
}
但vite创建的vue3则不可以通过require对图片进行动态绑定
可以通过一下方法进行绑定(注意vite根目录是/
,且vite会自动解析src中的字符串) 该方法在vue3中我并未测试,如果没效果 ,往下看其他方法
<script setup>
import { reactive } from "@vue/reactivity"const getImg = (name)=>{return `/src/assets/${name}.png`
}
const zyc = reactive({list:[{id:1,img:getImg("logo")},{id:2,img:getImg("logo")},{id:3,img:getImg("logo")}]
})
</script>
vue3:
在需要动态绑定src的时候,还是按照之前常规的方法 require(‘xxxx’ + 变量)
<div:class="['tag-item', currentSystem == item.code ? 'activeTag' : '']"v-for="(item, index) in schoolTagsList":key="index"@click="getCurrentTypeSchoolList(item)"><img class="tag-icon" :src="require(`../../assets/img/${item.code}.png`)" alt="" /> {{ item.value}}</div>
控制台报错
ReferenceError: require is not defined
解决:
在vite中不能使用require引入图片资源,因为这里的require貌似是webpack提供的一种加载能力,由于我们并非使用的webpack作为项目的构建工具,我们使用的是Vite,因此这里必须转用 Vite提供的静态资源载入,vite关于这一部分的官方说明在这里,有兴趣的小伙伴可以看官方的文档:Vite中静态资源处理;
官网案例解析如下:
可能不大好理解,简单的说 new URL
一共接收两个参数,第一个参数即图片的路径,这里就是对应require中的值,第二个参数是vite的一个全局变量,可以理解成直接写死了 import.meta.url
需要改下成如下
<div:class="['tag-item', currentSystem == item.code ? 'activeTag' : '']"v-for="(item, index) in schoolTagsList":key="index"@click="getCurrentTypeSchoolList(item)"><img class="tag-icon" :src="getImageUrl(item.code)" alt="" />{{ item.value }}</div><script>export default {setup() {const getImageUrl = (code) => {return new URL(`../../../assets/img/${code}.png`, import.meta.url).href;};return {getImageUrl,};},}
</script>
还有一种待测试方法是 根据官网提示:就是在将asset 前面加上src。
<img v-if="post.welcomeScreen" :src="`/src/assets/blogPhotos/${name}.jpg`" alt="" />
而直接用import这种方式可以在vue2 或者vue3都可以用
import imgUrl from './img.png'
document.getElementById('hero-img').src = imgUrl
接下来对vite提供的new URL
和import.meta.url
。这两种新知识做一个详解:
new URL()
创建一个新 URL 对象的语法:
new URL(url, [base])
- url —— 完整的 URL,或者仅路径(如果设置了 base),
- base —— 可选的 base URL:如果设置了此参数,且参数 url 只有路径,则会根据这个 base 生成 URL。
显而易见:
const path = new URL(`../assets/blogPhotos/${name}.jpg`, import.meta.url);
../assets/blogPhotos/${name}.jpg
是相对路径,而import.meta.url
是base url (根链接)。
可以将这个path打印出来:
{
hash: ""
host: "localhost:3000"
hostname: "localhost"
href: "http://localhost:3000/src/assets/blogPhotos/coding.jpg"
origin: "http://localhost:3000"
password: ""
pathname: "/src/assets/blogPhotos/coding.jpg"
port: "3000"
protocol: "http:"
search: ""
searchParams: URLSearchParams {}
username: ""
}
其中有一个属性是href
,正好是函数的返回值!
import.meta
import.meta
对象包含关于当前模块的信息。
它的内容取决于其所在的环境。在浏览器环境中,它包含当前脚本的 URL,或者如果它是在 HTML 中的话,则包含当前页面的 URL。
因此可以把import.meta
打印出来:
console.log(import.meta);
可以看到,它有一个属性就是url。
综上,终于理解了上面的那个函数。
function getImageUrl(name) {return new URL(`../assets/blogPhotos/${name}.jpg`, import.meta.url).href;
}