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 轻松支持函数重载 (Part 2 - 实现)
Aug 04 Javascript
JavaScript 学习笔记(六)
Dec 31 Javascript
iframe自适应宽度、高度 ie6 7 8,firefox 3.86下测试通过
Jul 29 Javascript
jQuery基础知识点总结(必看)
May 31 Javascript
Bootstrap基本样式学习笔记之表格(2)
Dec 07 Javascript
EasyUI折叠表格层次显示detailview详解及实例
Dec 28 Javascript
JSON中key动态设置及JSON.parse和JSON.stringify()的区别
Dec 29 Javascript
Angular.Js之Scope作用域的学习教程
Apr 27 Javascript
360提示[高危]使用存在漏洞的JQuery版本的解决方法
Oct 27 jQuery
详解Nuxt.js部署及踩过的坑
Aug 07 Javascript
详解vue在项目中使用百度地图
Mar 26 Javascript
JavaScript中十种一步拷贝数组的方法实例详解
Apr 22 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
如何删除多级目录
2006/10/09 PHP
php循环检测目录是否存在并创建(循环创建目录)
2011/01/06 PHP
php中$_GET与$_POST过滤sql注入的方法
2014/11/03 PHP
[原创]smarty简单模板变量输出方法
2016/07/09 PHP
PHP new static 和 new self详解
2017/02/19 PHP
php PDO实现的事务回滚示例
2017/03/23 PHP
利用PHPStorm如何开发Laravel应用详解
2017/08/30 PHP
tagName的使用,留一笔
2006/06/26 Javascript
Javascript基础 函数“重载” 详细介绍
2013/10/25 Javascript
javascript表格隔行变色加鼠标移入移出及点击效果的方法
2015/04/10 Javascript
vue 和vue-touch 实现移动端左右导航效果(仿京东移动站导航)
2017/04/22 Javascript
AngularJS中下拉框的基本用法示例
2017/10/11 Javascript
浅谈Node.js之异步流控制
2017/10/25 Javascript
Vue2.0学习之详解Vue 组件及父子组件通信
2017/12/12 Javascript
JavaScript如何获取一个元素的样式信息
2019/07/29 Javascript
JS实现旋转木马轮播图
2020/01/01 Javascript
angular中的post请求处理示例详解
2020/06/30 Javascript
JavaScript 判断浏览器是否是IE
2021/02/19 Javascript
python数据结构之二叉树的统计与转换实例
2014/04/29 Python
python如何读写csv数据
2018/03/21 Python
python 读取摄像头数据并保存的实例
2018/08/03 Python
python递归全排列实现方法
2018/08/18 Python
python利用小波分析进行特征提取的实例
2019/01/09 Python
python自动发邮件总结及实例说明【推荐】
2019/05/31 Python
基于多进程中APScheduler重复运行的解决方法
2019/07/22 Python
Python3批量移动指定文件到指定文件夹方法示例
2019/09/02 Python
python 通过邮件控制实现远程控制电脑操作
2020/03/16 Python
联想瑞士官方网站:Lenovo Switzerland
2017/11/19 全球购物
Quiksilver美国官网:始于1969年的优质冲浪服和滑雪板外套
2020/04/20 全球购物
2014年民政局关于保密工作整改措施
2014/09/19 职场文书
小学中队长竞选稿
2015/11/20 职场文书
演讲稿之开卷有益
2019/08/07 职场文书
大学生党员暑假实践(活动总结)
2019/08/21 职场文书
个人销售励志奋斗口号
2019/12/05 职场文书
js实现上传图片到服务器
2021/04/11 Javascript
MongoDB数据库之添删改查
2022/04/26 MongoDB