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 相关文章推荐
ajax页面无刷新 IE下遭遇Ajax缓存导致数据不更新的问题
Dec 11 Javascript
打印json对象的内容及JSON.stringify函数应用
Mar 29 Javascript
原生Js页面滚动延迟加载图片实现原理及过程
Jun 24 Javascript
JavaScript事件委托用法分析
Jan 24 Javascript
jQuery实现图片走马灯效果的原理分析
Jan 16 Javascript
12306 刷票脚本及稳固刷票脚本(防挂)
Jan 04 Javascript
微信小程序中hidden不生效原因的解决办法
Apr 26 Javascript
Node.js 的模块知识汇总
Aug 16 Javascript
vue2.x集成百度UEditor富文本编辑器的方法
Sep 21 Javascript
Express结合Webpack的全栈自动刷新
May 23 Javascript
vue动态配置模板 'component is'代码
Jul 04 Javascript
js+canvas实现转盘效果(两个版本)
Sep 13 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 socket编程
2015/05/13 PHP
laravel实现简单用户权限的示例代码
2019/05/28 PHP
php实现图片压缩处理
2020/09/09 PHP
一个选择最快的服务器转向代码
2009/04/27 Javascript
javascript 添加和移除函数的通用方法
2009/10/20 Javascript
利用jQuery 实现GridView异步排序、分页的代码
2010/02/06 Javascript
跨浏览器的事件对象介绍
2012/06/27 Javascript
Nodejs全栈框架StrongLoop推荐
2014/11/09 NodeJs
JavaScript 基本概念
2015/01/20 Javascript
jQuery插件ImageDrawer.js实现动态绘制图片动画(附源码下载)
2016/02/25 Javascript
jquery遍历json对象集合详解
2016/05/18 Javascript
Angular下H5上传图片的方法(可多张上传)
2017/01/09 Javascript
Web纯前端“旭日图”实现元素周期表
2017/03/10 Javascript
Angular中$broadcast和$emit的使用方法详解
2017/05/22 Javascript
利用Console来Debug的10个高级技巧汇总
2018/03/26 Javascript
NodeJS安装图文教程
2018/04/19 NodeJs
微信小程序实现点击按钮后修改颜色
2019/12/05 Javascript
JS数组的高级使用方法示例小结
2020/03/14 Javascript
python中日期和时间格式化输出的方法小结
2015/03/19 Python
python语言中with as的用法使用详解
2018/02/23 Python
对Django的restful用法详解(自带的增删改查)
2019/08/28 Python
python 使用pygame工具包实现贪吃蛇游戏(多彩版)
2019/10/30 Python
pycharm开发一个简单界面和通用mvc模板(操作方法图解)
2020/05/27 Python
收集的22款给力的HTML5和CSS3帮助工具
2012/09/14 HTML / CSS
html5构建触屏网站之touch事件介绍
2013/01/07 HTML / CSS
html5 实现客户端验证上传文件的大小(简单实例)
2016/05/15 HTML / CSS
英国著名的药妆网站:Escentual
2016/07/29 全球购物
H&M美国官网:欧洲最大的服饰零售商
2016/09/07 全球购物
销售员自我评价怎么写
2013/09/19 职场文书
《画杨桃》教学反思
2014/04/13 职场文书
驾驶员安全责任书范本
2014/07/24 职场文书
2014个人反腐倡廉思想汇报
2014/09/15 职场文书
医院保洁员岗位职责
2015/02/13 职场文书
幼儿园中班教育随笔
2015/08/14 职场文书
【TED出品】天梯非主流开心游1700 划水骑士
2022/03/31 魔兽争霸
Python sklearn分类决策树方法详解
2022/09/23 Python