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 尚未实现错误解决办法
Nov 27 Javascript
基于jQuery的让非HTML5浏览器支持placeholder属性的代码
May 24 Javascript
JS通过相同的name进行表格求和代码
Aug 18 Javascript
登陆成功后自动计算秒数执行跳转
Jan 23 Javascript
仿淘宝TAB切换搜索框搜索切换的相关内容
Sep 21 Javascript
jQuery使用之设置元素样式用法实例
Jan 19 Javascript
php基于redis处理session的方法
Mar 14 Javascript
Bootstrap自定义文件上传下载样式
May 26 Javascript
js获取html的span标签的值方法(超简单)
Jul 26 Javascript
JS中input表单隐藏域及其使用方法
Feb 13 Javascript
微信小程序中限制激励式视频广告位显示次数(实现思路)
Dec 06 Javascript
ES6学习笔记之let与const用法实例分析
Jan 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
PHP面向对象编程快速入门
2006/10/09 PHP
php中判断一个字符串包含另一个字符串的方法
2007/03/19 PHP
php连接Access数据库错误及解决方法
2013/06/20 PHP
PHP5.5和之前的版本empty函数的不同之处
2014/06/13 PHP
PHP数组去重的更快实现方式分析
2018/05/09 PHP
[原创]PHP global全局变量经典应用与注意事项分析【附$GLOBALS用法对比】
2019/07/12 PHP
超强的IE背景图片闪烁(抖动)的解决办法
2007/09/09 Javascript
function foo的原型与prototype属性解惑
2010/11/19 Javascript
Jquery实现三层遍历删除功能代码
2013/04/23 Javascript
js setTimeout 常见问题小结
2013/08/13 Javascript
JavaScript中跨域调用Flash的方法
2014/08/11 Javascript
嵌入式iframe子页面与父页面js通信的方法
2015/01/20 Javascript
每天一篇javascript学习小结(基础知识)
2015/11/10 Javascript
jQuery实现的左右移动焦点图效果
2016/01/14 Javascript
浅谈JavaScript 执行环境、作用域及垃圾回收
2016/05/31 Javascript
jQuery插件Echarts实现的渐变色柱状图
2017/03/23 jQuery
JS使用cookie实现只出现一次的广告代码效果
2017/04/22 Javascript
jQuery中each遍历的三种方法实例分析
2018/09/07 jQuery
vue下拉菜单组件(含搜索)的实现代码
2018/11/25 Javascript
深入理解使用Vue实现Context-Menu的思考与总结
2019/03/09 Javascript
vue下canvas裁剪图片实例讲解
2020/04/16 Javascript
在Vue 中获取下拉框的文本及选项值操作
2020/08/13 Javascript
WebStorm无法正确识别Vue3组合式API的解决方案
2021/02/18 Vue.js
Python中IPYTHON入门实例
2015/05/11 Python
python机器人行走步数问题的解决
2018/01/29 Python
pandas 使用apply同时处理两列数据的方法
2018/04/20 Python
浅析PyTorch中nn.Linear的使用
2019/08/18 Python
Java ExcutorService优雅关闭方式解析
2020/05/30 Python
利用纯CSS3实现动态的自行车特效源码
2017/01/20 HTML / CSS
html5 canvas绘制放射性渐变色效果
2018/01/04 HTML / CSS
如何通过jdbc调用存储过程
2012/04/19 面试题
实习生个人的自我评价
2013/12/08 职场文书
竞选部门副经理的自荐书范文
2014/02/11 职场文书
档案保密承诺书
2014/06/03 职场文书
什么是执行力?9个故事告诉您:成功绝非偶然!
2019/07/05 职场文书
Centos系统通过Docker安装并搭建MongoDB数据库
2022/04/12 MongoDB