Vue開發(fā)之封裝上傳文件組件與用法示例
更新時間:2019年04月25日 11:32:02 作者:guanguan0_0
這篇文章主要介紹了Vue開發(fā)之封裝上傳文件組件與用法,結(jié)合實例形式分析了vue.js使用elementui的 el-upload插件進行上傳文件組件的封裝及使用相關(guān)操作技巧,需要的朋友可以參考下
本文實例講述了Vue開發(fā)之封裝上傳文件組件與用法。分享給大家供大家參考,具體如下:
使用elementui的 el-upload插件實現(xiàn)圖片上傳組件
每個項目存在一定的特殊性,所以數(shù)據(jù)的處理會不同
pictureupload.vue:
<template> <div class="pictureupload"> <el-upload :action="baseUrl + '/api/public/image'" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :file-list="fileList" :on-exceed="handleExceed" :before-remove="beforeRemove" name="img" :on-success="upLoadSuccess" :data="upLoadData" :headers="headers" :limit="limit"> <i class="el-icon-plus"></i> </el-upload> <el-dialog :visible.sync="dialogVisible"> <img width="100%" :src="dialogImageUrl" alt=""> </el-dialog> </div> </template> <script> import { getToken } from "@/utils/auth"; import store from "@/store"; export default { props: { imgList: { type: Array, default: [] }, // 父組件傳遞的圖片列表 limit: "" // 圖片數(shù)量限制 }, data() { return { fileList: [], upLoadData: { img: "" }, baseUrl: process.env.BASE_API, dialogVisible: false, dialogImageUrl: "", headers: { Authorization: store.getters.token_type + " " + store.getters.token } // 接口調(diào)用token }; }, watch: { // 監(jiān)聽imgList的變化: fileList要求的格式為[{url: img}],所以監(jiān)聽imgList變化后將其進行處理,賦值給fileList imgList: { handler(newValue, oldValue) { if(newValue.length === 0) { this.fileList = []; return; } for (let i = 0; i < newValue.length; i++) { if (oldValue[i] != newValue[i]) { this.fileList = []; newValue.forEach(el => { this.fileList.push({url: el}) }) return; } } }, deep: true } }, methods: { // 圖片移除時處理數(shù)據(jù) handleRemove(file, fileList) { let item = []; fileList.forEach(el => { item.push(el.url); }); this.$emit("removeimg", item); }, handlePictureCardPreview(file) { this.dialogImageUrl = file.url; this.dialogVisible = true; }, // 判斷圖片數(shù)量 handleExceed(files, fileList) { this.$message.warning(`當前限制選擇 ${this.limit} 個文件,本次選擇了 ${files.length} 個文件,共選擇了 ${files.length + fileList.length} 個文件`); }, beforeRemove(file, fileList) {}, // 上傳圖片成功事件 upLoadSuccess(response) { this.$emit("uploadimg", response.message); this.$message("上傳成功",); } }, mounted() { if (this.imgList.length != 0) { this.imgList.forEach(el => { this.fileList.push({ url: el }); }); } } }; </script>
使用上傳圖片組件:
<pictureupload @uploadimg="uploadimg" :imgList="ruleForm.img" :limit="3" @removeimg="removeimg"></pictureupload>
removeimg(item) { this.ruleForm.img = item; }, uploadimg(item) { this.ruleForm.img.push(item); },
希望本文所述對大家vue.js程序設(shè)計有所幫助。
相關(guān)文章
Vue.js實現(xiàn)一個todo-list的上移下移刪除功能
這篇文章主要介紹了Vue.js實現(xiàn)一個todo-list的上移下移刪除功能,需要的朋友可以參考下2017-06-06vue單頁應(yīng)用在頁面刷新時保留狀態(tài)數(shù)據(jù)的方法
今天小編就為大家分享一篇vue單頁應(yīng)用在頁面刷新時保留狀態(tài)數(shù)據(jù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09