您的位置:首頁技術文章
文章詳情頁

vue實現圖片上傳功能

瀏覽:29日期:2023-01-18 16:51:41

本文實例為大家分享了vue實現圖片上傳功能的具體代碼,供大家參考,具體內容如下

先看效果

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 :src='http://www.wxshucaidpc.com/bcjs/item'/> <img src='http://www.wxshucaidpc.com/bcjs/@/assets/images/consult_close.png' @click='(e) => delImgClick(index, e)' /> </div> <!-- v-if='remUploadImgUrls.length < 6' 限制最多6張 --> <img src='http://www.wxshucaidpc.com/bcjs/@/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 :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實戰教程》

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Vue
相關文章:
国产综合久久一区二区三区