vue3循环展示图片

如图,根据 id 循环展示图片,网上搜了很多教程统统没有成功,终于自己踩坑踩好了,刷到位这个帖子的兄弟姐妹有福啦!!!

【关键代码1】

里面有两个参数,第一个参数是当前图片的地址,换成你自己的,第二个照写不用改

const getImageUrl=(name)=>{
  return new URL(`../../assets/images/home/${name}`, import.meta.url).href
}

【关键代码2】

注释的地方,可以先写一个能展示出来的图片地址,保证地址没问题,这样直接把当前地址复制到 getImageUrl 方法里面就行

<!-- <div><img src="../../assets/images/home/home.png" alt="" /></div> -->
<div><img :src="getImageUrl('home.png')" alt="" /></div>

Vue 3循环展示本地图片,可按以下步骤操作: ### 1. 整理图片数据 在组件的 `data` 选项(组合式 API 中使用 `reactive` 或 `ref`)里,把图片的路径用数组组合起来。例如: ```vue <template> <!-- 后续遍历图片的代码将写在这里 --> </template> <script setup> import { ref } from &#39;vue&#39;; // 使用 ref 定义响应式数据 const content_top = ref([ { title: &#39;图片1&#39;, src: &#39;./imges/a.png&#39;, key: &#39;0&#39; }, { title: &#39;图片2&#39;, src: &#39;./imges/b.png&#39;, key: &#39;1&#39; }, { title: &#39;图片3&#39;, src: &#39;./imges/c.png&#39;, key: &#39;2&#39; } ]); </script> ``` ### 2. 在模板中遍历数组 在 `template` 模块中把数组遍历出来。但需注意,直接使用路径图片可能加载不出来,因编译器对动态路径处理存在问题,需在路径前加 `require`。 ```vue <template> <div> <div v-for="item in content_top" :key="item.key"> <!-- 使用 require 处理图片路径 --> <img :src="require(item.src)" :alt="item.title"> <p>{{ item.title }}</p> </div> </div> </template> <script setup> import { ref } from &#39;vue&#39;; const content_top = ref([ { title: &#39;图片1&#39;, src: &#39;./imges/a.png&#39;, key: &#39;0&#39; }, { title: &#39;图片2&#39;, src: &#39;./imges/b.png&#39;, key: &#39;1&#39; }, { title: &#39;图片3&#39;, src: &#39;./imges/c.png&#39;, key: &#39;2&#39; } ]); </script> ``` ### 3. 处理路径拼接问题 若路径拼接较复杂,可编写一个函数处理。例如: ```vue <template> <div> <div v-for="item in content_top" :key="item.key"> <!-- 调用函数获取图片路径 --> <img :src="getImgUrl(item.src, &#39;png&#39;)" :alt="item.title"> <p>{{ item.title }}</p> </div> </div> </template> <script setup> import { ref } from &#39;vue&#39;; const content_top = ref([ { title: &#39;图片1&#39;, src: &#39;a&#39;, key: &#39;0&#39; }, { title: &#39;图片2&#39;, src: &#39;b&#39;, key: &#39;1&#39; }, { title: &#39;图片3&#39;, src: &#39;c&#39;, key: &#39;2&#39; } ]); // 处理图片路径的函数 const getImgUrl = (url, type) => { if (type === &#39;png&#39;) { const a = require(&#39;../../assets/img/index/&#39; + url + &#39;.png&#39;); return a; } else if (type === &#39;jpg&#39;) { const b = require(&#39;../../assets/img/index/&#39; + url + &#39;.jpg&#39;); return b; } }; </script> ``` ### 注意事项 - `assets` 在项目编译时会被 `webpack` 处理解析为模块依赖,只支持相对路径形式,加载图片模块通过 `webpack` 的 `url-loader` 加载器实现,而 `url-loader` 解析不了动态绑定的 `src`,所以要用相对路径 `src` 引入 [^2]。 - `required` 引入路径需要拼接,不能直接 `required(imgpath)` [^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值