Vue+Vant 图片上传加显示的案例


Posted in Javascript onNovember 03, 2020

前端开发想省时间就是要找框架呀!找框架!

vant中上传图片组件:https://youzan.github.io/vant/#/zh-CN/uploader

上传图片的组件uploader:

<van-uploader :after-read="onRead" accept="image/*" multiple>
   <imgclass="head-img" src="/static/images/addpic.png" ref="goodsImg"/>
 </van-uploader>

method中

methods: {
      //选择图片后执行
  onRead(file) {
     console.log(file);
     //将原图片显示为选择的图片
     this.$refs.goodsImg.src = file.content;
   }
 }

vant上传的图片是已经base64处理了的,可以直接向后台发了

补充知识:vue +vant + crodova实现图片上传、图片预览、图片删除

函数调用方法使用图片预览有坑,图片不显示

Vue+Vant 图片上传加显示的案例

<template>
 <div class="add-check-page">
  <head-com :title="title"></head-com>
  <van-form @submit="onSubmit">
   <h2 class="van-doc-demo-block__title">添加照片</h2>
   <van-field name="uploader" class="pic-uploader">
    <template #input>
     <template v-for="(item, index) in file_path">
      <div class="item" :key="index">
       <van-image fit="cover" :src="IP + item" @click="preView(index)">
        <template v-slot:loading>
         <van-loading type="spinner" size="20" />
        </template>
       </van-image>
       <van-icon name="close" @click="delPic(index)" />
      </div>
     </template>
     <van-icon class="up-btn" @click="picture" :name="require('#/images/add_check_icon.png')" />
     <van-uploader id="photo" multiple :after-read="afterRead" style="display:none">
      <van-button
       class="up-btn"
       :icon="require('#/images/add_check_icon.png')"
       type="default"
      />
     </van-uploader>
    </template>
   </van-field>
   <van-button class="save" block type="default" native-type="submit">确认提交</van-button>
  </van-form>
  <van-action-sheet
   v-model="show"
   :actions="actions"
   @select="onSelect"
   cancel-text="取消"
   close-on-click-action
  />
  <loading :showLoading="showLoad"></loading>
  // 使用函数调用图片预览方法,图片无法显示所以改用组件调用
  <van-image-preview
   v-if="imgShow"
   v-model="imgShow"
   :images="preList"
   :start-position="startIndex"
   @closed="handleClose"
  ></van-image-preview>
 </div>
</template>
<script>
import headCom from '_c/header/index.vue'
import loading from '_c/loading/index.vue'
export default {
 components: {
  headCom,
  loading
 },
 data() {
  return {
   //  公司id
   id: '',
   id2: '',
   title: '',
   file_name: [],
   file_path: [],
   content: '',
   show: false,
   actions: [{ name: '拍摄' }, { name: '从手机相册选择' }],
   showLoad: false,
   imgPre: '',
   imgShow: false,
   preList: [],
   startIndex: 0
  }
 },
 beforeRouteLeave(to, from, next) {
  if (this.imgPre) {
   this.imgPre.close()
  }
  next()
 },
 created() {
  this.id = this.$route.params.id
  if (this.$route.name === 'editCheck') {
   this.title = '编辑记录'
   this.getInfo()
  } else {
   this.title = '添加记录'
  }
 },
 methods: {
  async getInfo() {
   this.showLoad = true
   try {
    let data = {
     id: this.id
    }
    let res = await this.$api.check.edit(data)
    this.content = res.detail.content
    this.id2 = res.detail.company_id
    res.photo_list.forEach((item) => {
     this.file_name.push(item.file_name)
     this.file_path.push(item.file_path)
    })
    this.showLoad = false
   } catch (error) {
    this.showLoad = false
    this.$toast(error.msg)
   }
  },
  async onSubmit(values) {
   this.showLoad = true
   try {
    let data = {}
    if (this.$route.name === 'editCheck') {
     data = {
      id: this.id,
      company_id: this.id2,
      content: values.content,
      file_names: [...this.file_name],
      file_paths: [...this.file_path]
     }
     await this.$api.check.editPost(data)
    } else {
     // 添加
     data = {
      company_id: this.id,
      content: values.content,
      file_names: [...this.file_name],
      file_paths: [...this.file_path]
     }
     await this.$api.check.addPost(data)
    }
    this.showLoad = false
    this.$router.go(-1)
   } catch (error) {
    this.$toast(error.msg)
   }
  },
  // 删除图片
  delPic(index) {
   this.file_path.splice(index, 1)
   this.file_name.splice(index, 1)
  },
  // 图片预览
  preView(index) {
   this.startIndex = index
   this.preList = []
   this.file_path.forEach((item) => {
    this.preList.push(this.IP + item)
   })
   this.imgShow = true
  },
  // 关闭预览
  handleClose() {
   this.preList = []
   this.imgShow = false
  },
  async afterRead(file) {
   this.showLoad = true
   try {
    if (file.length) {
     file.forEach(async (item) => {
      let res = await this.$api.base.upload(item)
      this.file_name.push(res.name)
      this.file_path.push(res.url)
      this.showLoad = false
     })
    } else {
     let res = await this.$api.base.upload(file)
     this.file_name.push(res.name)
     this.file_path.push(res.url)
     this.showLoad = false
    }
   } catch (e) {
    this.showLoad = false
    this.$toast(e.data)
   }
  },
  picture() {
   this.show = true
  },
  // 选择添加图片方式
  onSelect(item) {
   this.show = false
   if (item.name === '拍摄') {
    this.takePhoto()
   } else {
    let dl = document.getElementById('photo')
    dl.click()
   }
  },
  // 拍照上传
  takePhoto() {
   let that = this
   // crodova 调取相机拍照
   navigator.camera.getPicture(success, error, {})
   function success(imageURI) {
    that.showLoad = true
    // file uri 上传服务器
    that.fileUpload(imageURI)
   }
   function error() {
    this.$toast('打开相机失败')
   }
  },
  // 使用cordova FileUpload上传图片
  fileUpload: function(imageURI) {
   let that = this
   let FileUploadOptions = window.FileUploadOptions
   let FileTransfer = window.FileTransfer
   let options = new FileUploadOptions()
   options.fileKey = 'file'
   options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1)
   options.mimeType = 'image/jpeg'
   let ft = new FileTransfer()
   ft.upload(imageURI, encodeURI(this.API + '/user/uploadImg'), function(data) {
    let resString = data.response
    let resObject = JSON.parse(resString) // 字符串转对象
    if (resObject.code === 1) {
     that.file_name.push(resObject.data.name)
     that.file_path.push(resObject.data.url)
     that.showLoad = false
    } else {
     that.showLoad = false
     that.$toast(resObject.msg)
    }
   })
  }
 }
}
</script>

以上这篇Vue+Vant 图片上传加显示的案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
面向对象的Javascript之三(封装和信息隐藏)
Jan 27 Javascript
jQuery时间轴插件使用详解
Jul 16 Javascript
JavaScript仿静态分页实现方法
Aug 04 Javascript
JavaScript计划任务后台运行的方法
Dec 18 Javascript
jQuery动态创建元素以及追加节点的实现方法
Oct 20 Javascript
深入理解JS继承和原型链的问题
Dec 17 Javascript
原生Javascript插件开发实践
Jan 09 Javascript
JavaScript正则获取地址栏中参数的方法
Mar 02 Javascript
vue-cli与webpack处理静态资源的方法及webpack打包的坑
May 15 Javascript
vue中子组件调用兄弟组件方法
Jul 06 Javascript
JavaScript展开操作符(Spread operator)详解
Jul 20 Javascript
vue点击当前路由高亮小案例
Sep 26 Javascript
vant-ui AddressEdit地址编辑和van-area的用法说明
Nov 03 #Javascript
antd中table展开行默认展示,且不需要前边的加号操作
Nov 02 #Javascript
React Ant Design树形表格的复杂增删改操作
Nov 02 #Javascript
vue缓存之keep-alive的理解和应用详解
Nov 02 #Javascript
详解vue-router的导航钩子(导航守卫)
Nov 02 #Javascript
vue+elementUI中表格高亮或字体颜色改变操作
Nov 02 #Javascript
vue element-ui中table合计指定列求和实例
Nov 02 #Javascript
You might like
在Windows系统上安装PHP运行环境文字教程
2010/07/19 PHP
javascript 设置文本框中焦点的位置
2009/11/20 Javascript
JavaScript随机排序(随即出牌)
2010/09/17 Javascript
jQuery ui 利用 datepicker插件实现开始日期(minDate)和结束日期(maxDate)
2014/05/22 Javascript
JavaScript实现列出数组中最长的连续数
2014/12/29 Javascript
jQuery实现右侧显示可向左滑动展示的深色QQ客服效果代码
2015/10/23 Javascript
解析浏览器端的AJAX缓存机制
2016/06/21 Javascript
利用Angularjs和Bootstrap前端开发案例实战
2016/08/27 Javascript
js+css实现打字效果
2020/06/24 Javascript
详解webpack模块加载器兼打包工具
2018/09/11 Javascript
Layui 带多选框表格监听事件以及按钮自动点击写法实例
2019/09/02 Javascript
基于aotu.js实现微信自动添加通讯录中的联系人功能
2020/05/28 Javascript
VUE使用 wx-open-launch-app 组件开发微信打开APP功能
2020/08/11 Javascript
基于JS实现快速读取TXT文件
2020/08/25 Javascript
nodejs中的异步编程知识点详解
2021/01/17 NodeJs
Python 过滤字符串的技巧,map与itertools.imap
2008/09/06 Python
python元组操作实例解析
2014/09/23 Python
初步剖析C语言编程中的结构体
2016/01/16 Python
初学python的操作难点总结(新手必看篇)
2017/08/03 Python
轻松实现TensorFlow微信跳一跳的AI
2018/01/05 Python
Python机器学习之scikit-learn库中KNN算法的封装与使用方法
2018/12/14 Python
Pycharm 文件更改目录后,执行路径未更新的解决方法
2019/07/19 Python
关于Tensorflow使用CPU报错的解决方式
2020/02/05 Python
keras中的backend.clip用法
2020/05/22 Python
python matplotlib库的基本使用
2020/09/23 Python
Python 微信公众号文章爬取的示例代码
2020/11/30 Python
python爬虫scrapy框架的梨视频案例解析
2021/02/20 Python
CSS3实现网站商品展示效果图
2020/01/18 HTML / CSS
使用html5实现表格实现标题合并的实例代码
2019/05/13 HTML / CSS
90后毕业生的求职信范文
2013/09/21 职场文书
实习教师自我鉴定
2013/12/12 职场文书
优化经济发展环境工作总结
2015/08/11 职场文书
Apache Pulsar集群搭建部署详细过程
2022/02/12 Servers
Java 深入探究讲解简单工厂模式
2022/04/07 Java/Android
《群青的幻想曲》京力秋树角色PV公开
2022/04/08 日漫
mysqldump进行数据备份详解
2022/07/15 MySQL