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学习笔记(九)javascript中的原型(prototype)及原型链的继承方式
Apr 12 Javascript
JavaScipt选取文档元素的方法(推荐)
Aug 05 Javascript
懒加载实现的分页&amp;&amp;网站footer自适应
Dec 21 Javascript
js读取json文件片段中的数据实例
Mar 09 Javascript
详解关于react-redux中的connect用法介绍及原理解析
Sep 11 Javascript
vue实现登陆登出的实现示例
Sep 15 Javascript
jQuery实现table中两列CheckBox只能选中一个的示例
Sep 22 jQuery
javascript实现数字配对游戏的实例讲解
Dec 14 Javascript
微信开发之企业付款到银行卡接口开发的示例代码
Sep 18 Javascript
layui table动态表头 改变表格头部 重新加载表格的方法
Sep 21 Javascript
vue遍历对象中的数组取值示例
Nov 07 Javascript
element-ui树形控件后台返回的数据+生成组织树的工具类
Mar 05 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对csv文件的读取,写入,输出下载操作详解
2013/08/10 PHP
PHP header()函数常用方法总结
2014/04/11 PHP
PHP实现的简单排列组合算法应用示例
2017/06/20 PHP
AngularJS入门教程之Hello World!
2014/12/06 Javascript
jQuery on方法传递参数示例
2014/12/09 Javascript
SyntaxHighlighter 3.0.83使用笔记
2015/01/26 Javascript
JavaScript中的Repaint和Reflow用法详解
2015/07/27 Javascript
javascript中Date format(js日期格式化)方法小结
2015/12/17 Javascript
JS中dom0级事件和dom2级事件的区别介绍
2016/05/05 Javascript
jquery基本选择器匹配多个元素的实现方法
2016/09/05 Javascript
JS实现类似51job上的地区选择效果示例
2016/11/17 Javascript
JavaScript实现父子dom同时绑定两个点击事件,一个用捕获,一个用冒泡时执行顺序的方法
2017/03/30 Javascript
深入理解基于vue-cli的vuex配置
2017/07/24 Javascript
ionic2懒加载配置详解
2017/09/01 Javascript
深入理解ES6 Promise 扩展always方法
2017/09/26 Javascript
react学习笔记之state以及setState的使用
2017/12/07 Javascript
jQuery点击页面其他部分隐藏下拉菜单功能
2018/11/27 jQuery
JavaScript中CreateTextFile函数
2020/08/30 Javascript
[02:44]DOTA2英雄基础教程 钢背兽
2013/12/19 DOTA
Python中类型关系和继承关系实例详解
2015/05/25 Python
python实现本地图片转存并重命名的示例代码
2018/10/27 Python
python判断完全平方数的方法
2018/11/13 Python
python3在同一行内输入n个数并用列表保存的例子
2019/07/20 Python
Python对Excel按列值筛选并拆分表格到多个文件的代码
2019/11/05 Python
Pandas的Apply函数具体使用
2020/07/21 Python
一款纯css3实现简单的checkbox复选框和radio单选框
2014/11/05 HTML / CSS
canvas小画板之平滑曲线的实现
2020/08/12 HTML / CSS
外科实习自我鉴定
2013/10/06 职场文书
涉外文秘个人求职的自我评价
2013/10/07 职场文书
护士辞职信模板
2014/01/20 职场文书
小学生打架检讨书
2014/01/26 职场文书
有多年工作经验的自我评价
2014/03/02 职场文书
大气污染防治方案
2014/05/19 职场文书
我们的节日端午节活动总结
2015/02/11 职场文书
Nginx本地目录映射实现代码实例
2021/03/31 Servers
Linux中sftp常用命令整理
2022/06/28 Servers