菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
70
0

vue基于vant的uploader上传图片

原创
05/13 14:22
阅读数 2213

小白第一次使用有赞的vant组件库, 这里记录一下个人在项目上的一些使用, 方便以后查阅.


<ul class="shop-list">
  <li class="list-item" v-for="(item, index) in shopList.items" :key="index">
    <div class="item-top-t">
      <div class="item-info" :order_code="item.order_code">
        <img class="item-img" :src="item.sku_pic_url" alt />
        <div class="item-t">
          <p class="item-title">{{item.goods_title}}</p>
          <p class="item-specs">{{item.sku_param_value}}</p>
        </div>
      </div>
      <div class="star">
        <span class="joyful">愉悦值:</span>
        <van-rate v-model="item.rate_num" :size="18" color="#f44" void-icon="star" void-color="#eee" />
      </div>
    </div>
    <div class="comment-main">
      <textarea v-model="item.comment" rows="3" cols="20" class="comment" type="text"
        placeholder="商品评价"  @blur="initScroll(index, $event)"></textarea>
    </div>
    <div class="upload">
      <van-uploader :name="index" :before-delete="delImgs" :after-read="uploadImgs"
        v-model="item.fileList" :max-count="5">
        <div class="upload-main">
          <img class="upload-img" src="@/assets/images/mihepink/w7.png" alt="">
          <p
          >上传图片</p>
        </div>
      </van-uploader>
    </div>
  </li>
</ul>

因为是一个商城项目, 所以DOM结构稍微有点多, li代表每个商品, 因为一个订单里不可能只有一个商品, 所以这里使用循环。
这里主要介绍一下van-uploader上面的属性和方法:
name:标识符,可以在回调函数的第二项参数中获取;
before-delete:文件删除前的回调函数;
after-read:文件读取完成后的回调函数;
v-model:绑定已经上传的图片列表,并展示图片列表的预览图;
max-count:文件上传数量限制;
这里是项目中使用到的一些属性,官网上会有更加详细的介绍:https://youzan.github.io/vant/#/zh-CN/uploader


/*上传图片*/
uploadImgs(file, name) {
  let data = new FormData();    
  let sub = name.name;  //标识, 使用的商品的索引
  //file是当前file对象, 此对象包含file和content
  data.append("picture", file.file);    
  this.$http
    .post(
      `URL`,
      data,
      {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      }
    )
    .then(res => {
      if (res.data.statusCode == 200) {
      /*因为是评价功能, 还需要把图片传到后台, 这里先存一下*/
        this.shopList.items[sub].uploadImgs.push(res.data.picture);
      }
    });
},

/*点击删除图片*/
delImgs(file, name) {
    //标识, 使用的商品的索引
  let sub = name.name; 
  //uploadImgs是要传递给后台的图片数组
  //name.index代表图片的索引
  this.shopList.items[sub].uploadImgs.splice(name.index, 1);
  //fileList是展示预览的图片数组
  this.shopList.items[sub].fileList.splice(name.index, 1);
},

以上就是本人项目中使用到的上传图片, 如果有哪些不足或错误, 欢迎留言评论。

发表评论

0/200
70 点赞
0 评论
收藏
为你推荐 换一批