vue实现图片上传功能
程序员文章站
2022-07-06 17:37:42
本文实例为大家分享了vue实现图片上传功能的具体代码,供大家参考,具体内容如下先看效果图片上传使用vant组件库中的 van-uploader, 使用方法参考官网vant组件库下面看代码uploadp...
本文实例为大家分享了vue实现图片上传功能的具体代码,供大家参考,具体内容如下
先看效果
图片上传使用vant组件库中的 van-uploader, 使用方法参考官网
vant组件库
下面看代码
uploadpicture.vue
<template> <div class="content"> <!-- 底部模块start --> <div class="bottom_bg"> <p class="flexst pt8">上传图片</p> <div class="upload_bg"> <div v-for="(item, index) in this.remuploadimgurls"> <img class="showimg" :src="item"/> <img class="delicon" src="@/assets/images/consult_close.png" @click="(e) => delimgclick(index, e)" /> </div> <!-- v-if="remuploadimgurls.length < 6" 限制最多6张 --> <img class="addimg" src="@/assets/images/inq_addimg.png" v-if="remuploadimgurls.length < 6" @click="openmenu" /> </div> </div> <!-- 底部模块end--> <van-actionsheet v-model="menushow" :actions="actions" cancel-text="取消" @select="onselect" /> <van-uploader id="upload" :after-read="onread"/> </div> </template> <script> import {mapstate} from 'vuex' export default { name: "uploadpicture", data() { return { menushow: false, actions: [ { name: '历史照片' }, { name: '选择相册或拍照' } ], } }, computed: { ...mapstate({ remuploadimgurls() { return this.$store.state.uploadimgurls; } }) }, methods: { openmenu() { this.menushow = true }, onselect(item) { this.menushow = false console.log(item); if (item.name === '选择相册或拍照') { return document.getelementbyid('upload').click(); } }, onread(file) { this.$store .dispatch({ type: 'uploadimg', payload: file.file }) .then(() => { // toast.clear; }); }, delimgclick(index, e) { let tmplist = [...this.remuploadimgurls]; tmplist.splice(index, 1); this.$store.commit('del_uploadimg', tmplist); } }, } </script> <style scoped lang="scss"> .content { .bottom_bg { margin: 10px 8px 0; padding: 0 .1rem; background: #fff; .upload_bg { margin-top: 10px; display: flex; justify-content: space-between; flex-wrap: wrap; div { width: 31%; margin-bottom: 10px; position: relative; .showimg { width: 100%; height: 100%; } .delicon { position: absolute; right: -6px; top: -6px; width: 20px; height: 20px; } } .addimg { width: 31%; height: 31%; margin-bottom: 10px; } &:after { width: 30%; content: ''; } } } } </style>
src/store/index.js
import vue from 'vue'; import vuex from 'vuex'; import { get, post} from '@/api'; vue.use(vuex); export default new vuex.store({ module: { }, state: { uploadimgurls: [], }, mutations: { // 处理同步方法 set_uploadimg(state, imgurl) { const tmp = state.uploadimgurls; tmp.push(imgurl); state.uploadimgurls = tmp; }, del_uploadimg(state, data) { state.uploadimgurls = [...data]; }, }, actions: { // 处理异步方法 // 上传图片 async uploadimg({ commit }, { payload }) { let f = new formdata(); f.append('file', payload); const data = await post('/upload', f); commit('set_uploadimg', data); }, }, });
更多文章可以点击《vue.js前端组件学习教程》学习阅读。
关于vue.js组件的教程,请大家点击专题vue.js组件学习教程进行学习。
更多vue学习教程请阅读专题《vue实战教程》
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: 千古一帝还是一代昏君,哪个才是真实的刘禅