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 相关文章推荐
jquery ready()的几种实现方法小结
Jun 18 Javascript
用js判断页面刷新或关闭的方法(onbeforeunload与onunload事件)
Jun 22 Javascript
js实现点击注册按钮开始读秒倒计时的小例子
May 11 Javascript
在JavaScript中使用NaN值的方法
Jun 05 Javascript
JavaScript实现经典排序算法之选择排序
Dec 28 Javascript
Javascript中数组去重与拍平的方法示例
Feb 03 Javascript
H5实现仿flash效果的实现代码
Sep 29 Javascript
vue数组对象排序的实现代码
Jun 20 Javascript
layui前端框架之table表数据的刷新方法
Aug 17 Javascript
大转盘抽奖小程序版 转盘抽奖网页版
Apr 16 Javascript
vue.js基于v-for实现批量渲染 Json数组对象列表数据示例
Aug 03 Javascript
Ajax实现异步加载数据
Nov 17 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
PHP获取数组中单列值的方法
2017/06/10 PHP
Yii2框架实现利用mpdf创建pdf文件功能示例
2019/02/08 PHP
php post换行的方法
2020/02/03 PHP
JQuery SELECT单选模拟jQuery.select.js
2009/11/12 Javascript
使用jquery与图片美化checkbox和radio控件的代码(打包下载)
2010/11/11 Javascript
兼容ie、firefox的图片自动缩放的css跟js代码分享
2013/08/12 Javascript
jquery表单验证插件(jquery.validate.js)的3种使用方式
2015/03/28 Javascript
JS实现向表格行添加新单元格的方法
2015/03/30 Javascript
javascript针对不确定函数的执行方法
2015/12/16 Javascript
jQuery form插件之ajaxForm()和ajaxSubmit()的可选参数项对象
2016/01/23 Javascript
jQuery基于$.ajax设置移动端click超时处理方法
2016/05/14 Javascript
Javascript+CSS3实现进度条效果
2016/10/28 Javascript
JavaScript实现的搜索及高亮显示功能示例
2017/08/14 Javascript
基于ajax和jsonp的原生封装(实例)
2017/10/16 Javascript
实例讲解javascript实现异步图片上传方法
2017/12/05 Javascript
React 组件转 Vue 组件的命令写法
2018/02/28 Javascript
深入浅析Vue中的 computed 和 watch
2018/06/06 Javascript
laydate时间日历插件使用方法详解
2018/11/14 Javascript
Vue3 的响应式和以前有什么区别,Proxy 无敌?
2020/05/20 Javascript
[01:34]完美“圣”典宣传片震撼发布,12.17与你不见不散
2016/12/16 DOTA
Python 过滤字符串的技巧,map与itertools.imap
2008/09/06 Python
用python分割TXT文件成4K的TXT文件
2009/05/23 Python
python标准日志模块logging的使用方法
2013/11/01 Python
简单的抓取淘宝图片的Python爬虫
2014/12/25 Python
在Python上基于Markov链生成伪随机文本的教程
2015/04/17 Python
整理Python最基本的操作字典的方法
2015/04/24 Python
python通过smpt发送邮件的方法
2015/04/30 Python
Python验证文件是否可读写代码分享
2017/12/11 Python
pycharm远程linux开发和调试代码的方法
2018/07/17 Python
20行Python代码实现一款永久免费PDF编辑工具的实现
2020/08/27 Python
美国最大的存储市场:SpareFoot
2018/07/23 全球购物
介绍一下linux的文件权限
2012/02/15 面试题
汽车技术服务英文求职信范文
2014/01/02 职场文书
《走一步再走一步》教学反思
2014/02/15 职场文书
2015年世界无烟日演讲稿
2015/03/18 职场文书
2016年“我们的节日·清明节”活动总结
2016/04/01 职场文书