当前位置: 首页 > news >正文

vue2中封装图片上传获取方法类(针对后端返回的数据不是图片链接,只是图片编号)

在Vue 2中实现商品列表中带有图片编号,并将返回的图片插入到商品列表中,可以通过以下步骤完成:

在Vue组件的data函数中定义商品列表和图片URL数组。
创建一个方法来获取每个商品的图片URL。
使用v-for指令在模板中遍历商品列表,并显示商品名称和图片。
下面是一个简单的Vue 2组件示例:

<template><div><div v-for="(product, index) in productList" :key="product.id" class="product"><img :src="product.imageUrl" :alt="product.name" class="product-image" /><p>{{ product.name }}</p></div></div>
</template><script>
export default {name: 'ProductList',data() {return {productList: [{ id: 1, name: 'Product 1', imageId: 'image1' },{ id: 2, name: 'Product 2', imageId: 'image2' },// ... 更多商品],// 初始化imageUrls数组,用于存储每个商品的图片URLimageUrls: []};},created() {this.fetchImages();},methods: {async fetchImages() {try {// 清空图片URL数组this.imageUrls = [];// 为每个商品获取图片URLfor (const product of this.productList) {const response = await fetch(`https://example.com/api/images/${product.imageId}`);const data = await response.json();this.imageUrls.push(data.imageUrl); // 假设API返回的JSON对象包含imageUrl字段}// 将图片URL分配给对应的商品this.productList.forEach((product, index) => {product.imageUrl = this.imageUrls[index];});} catch (error) {console.error('Error fetching images:', error);}}}
};
</script><style>
.product {margin-bottom: 20px;
}
.product-image {width: 100px; /* 根据需要调整图片大小 */height: auto;
}
</style>

在这个组件中,productList数组包含了商品的基本信息和图片编号。在组件创建时(created生命周期钩子),调用fetchImages方法来异步获取每个商品的图片URL。获取到图片URL后,将它们分配给productList数组中对应的商品对象。

模板部分使用v-for指令遍历productList,为每个商品渲染一个包含图片和名称的div元素。图片的src属性绑定到商品对象的imageUrl属性上。

请注意,这个示例假设你的后端API返回的JSON对象包含一个imageUrl字段。根据你的实际API响应结构,可能需要调整代码。此外,错误处理在这个示例中被简化了,你可能需要根据你的具体需求来增强错误处理逻辑。

封装一个类来实现这个图片转化方法

// ImageService.jsclass ImageService {constructor(apiBaseUrl) {this.apiBaseUrl = apiBaseUrl;}async fetchImageUrl(imageId) {const response = await fetch(`${this.apiBaseUrl}/images/${imageId}`);if (!response.ok) {throw new Error('Network response was not ok');}const data = await response.json();return data.imageUrl || null;}
}// 创建一个单例实例
const imageService = new ImageService('https://example.com/api');
export default imageService;

然后,在Vue组件中使用这个类:

<template><div><div v-for="(product, index) in productList" :key="product.id" class="product"><img :src="product.imageUrl" :alt="product.name" class="product-image" /><p>{{ product.name }}</p></div></div>
</template><script>
import imageService from './ImageService.js'; // 引入ImageService类export default {name: 'ProductList',data() {return {productList: [{ id: 1, name: 'Product 1', imageId: 'image1' },{ id: 2, name: 'Product 2', imageId: 'image2' },// ... 更多商品]};},created() {this.loadProductImages();},methods: {async loadProductImages() {try {for (let product of this.productList) {const imageUrl = await imageService.fetchImageUrl(product.imageId);if (imageUrl) {product.imageUrl = imageUrl;}}} catch (error) {console.error('Error fetching images:', error);}}}
};
</script><style>
.product {margin-bottom: 20px;
}
.product-image {width: 100px; /* 根据需要调整图片大小 */height: auto;
}
</style>

在这个Vue组件中,我们引入了ImageService类,并在组件创建时调用loadProductImages方法。这个方法遍历productList数组,为每个商品调用ImageService的fetchImageUrl方法来获取图片URL,并更新商品对象的imageUrl属性。

请注意,这个示例假设你的后端API返回的JSON对象包含一个imageUrl字段,并且ImageService类是一个单例,这意味着无论你在哪里使用它,都会是同一个实例。根据你的实际API响应结构和项目需求,可能需要调整代码。此外,错误处理在这个示例中被简化了,你可能需要根据你的具体需求来增强错误处理逻辑。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • iCloud完全指南:释放Apple云服务的终极潜力
  • 实验八、地址解析协议《计算机网络》
  • Java学习 - MyBatis - 初识MyBatis
  • MySQL数据库---LIMIT、EXPLAIN详解
  • jmeter并发测试
  • C++中实现一个泄漏检测工具
  • 软考初级网络管理员_01_计算机系统基础知识(硬件)单选题
  • 车载电子电气架构 --- 车载信息安全
  • 优思学院|谈汽车零部件企业生产精益及现场管理
  • 如何做好电子内窥镜的网络安全管理?
  • Leetcode 3179. Find the N-th Value After K Seconds
  • 新手上路:Linux虚拟机创建与Hadoop集群配置指南①(未完)
  • 一个开源的Office软件,很离谱的办公神器
  • dos命令---根据端口查找进程
  • mysql 定时执行 查询动态表名插入汇总表的sql
  • 【Redis学习笔记】2018-06-28 redis命令源码学习1
  • ➹使用webpack配置多页面应用(MPA)
  • 3.7、@ResponseBody 和 @RestController
  • js对象的深浅拷贝
  • Js基础知识(一) - 变量
  • js继承的实现方法
  • js中的正则表达式入门
  • JS专题之继承
  • Redux 中间件分析
  • select2 取值 遍历 设置默认值
  • Solarized Scheme
  • Spring Boot MyBatis配置多种数据库
  • Three.js 再探 - 写一个跳一跳极简版游戏
  • vue-cli3搭建项目
  • 百度贴吧爬虫node+vue baidu_tieba_crawler
  • 分享几个不错的工具
  • 码农张的Bug人生 - 初来乍到
  • 小试R空间处理新库sf
  • ​无人机石油管道巡检方案新亮点:灵活准确又高效
  • #微信小程序:微信小程序常见的配置传旨
  • #中的引用型是什么意识_Java中四种引用有什么区别以及应用场景
  • $.extend({},旧的,新的);合并对象,后面的覆盖前面的
  • (02)Cartographer源码无死角解析-(03) 新数据运行与地图保存、加载地图启动仅定位模式
  • (DenseNet)Densely Connected Convolutional Networks--Gao Huang
  • (k8s中)docker netty OOM问题记录
  • (第27天)Oracle 数据泵转换分区表
  • (力扣题库)跳跃游戏II(c++)
  • (四) 虚拟摄像头vivi体验
  • (五)网络优化与超参数选择--九五小庞
  • (学习日记)2024.01.19
  • (一) storm的集群安装与配置
  • (一)基于IDEA的JAVA基础12
  • (转)Linux下编译安装log4cxx
  • (转)Sql Server 保留几位小数的两种做法
  • (转)用.Net的File控件上传文件的解决方案
  • (转载)虚函数剖析
  • .ai域名是什么后缀?
  • .NET Remoting Basic(10)-创建不同宿主的客户端与服务器端
  • .Net(C#)常用转换byte转uint32、byte转float等
  • .NET的微型Web框架 Nancy