1、先上代碼:vueUpload.js
var dom = `<div class="upload-file"><el-upload :action="uploadFileUrl" :before-upload="handleBeforeUpload" :file-list="fileList" :limit="limit":on-error="handleUploadError" :on-exceed="handleExceed" :on-success="handleUploadSuccess":show-file-list="false" :headers="headers" class="upload-file-uploader" ref="upload"><!-- 上傳按鈕 --><el-button size="mini" type="primary">選取文件</el-button><!-- 上傳提示 --><div class="el-upload__tip" slot="tip" v-if="showTip">請上傳<template v-if="fileSize"> 大小不超過 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template><template v-if="fileType"> 格式為 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>的文件</div></el-upload><!-- 文件列表 --><div><div :key="file.uid" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in list"v-if="file.url != null" style="display:flex;justify-content:space-between;align-item:center;max-width:300px;over-flow:hidden;text-overflow:ellipsis;white-space:nowrap;border: 1px solid #ddd;padding: 0 10px;cursor: pointer;"><el-link :href="file.url" :underline="false" target="_blank"><span class="el-icon-document"> {{ file.name }} </span></el-link><div class="ele-upload-list__item-content-action"><el-link :underline="false" @click="handleDelete(index)" type="danger">刪除</el-link></div></div></div></div>`var demoComponent = Vue.extend({template:dom,props: {// 值value: [String, Object, Array],// 大小限制(MB)fileSize: {type: Number,default: 5,},// 文件類型, 例如['png', 'jpg', 'jpeg']fileType: {type: Array,default: () => ["doc", "xls", "ppt", "txt", "pdf"],},// 是否顯示提示isShowTip: {type: Boolean,default: true},limit: {type: Number,default: 9}},data:function(){return {uploadFileUrl: '/file/rest/common/upload', // 上傳的圖片服務器地址headers: {Authorization: 'Bearer 123'},fileList: [],}},created() {this.fileList = this.list;},mounted() {console.log(this);},computed: {// 是否顯示提示showTip() {return this.isShowTip && (this.fileType || this.fileSize);},// 列表list() {let temp = 1;if (this.value) {const list = this.value;return list.map((item) => {item.name = item.fileNameitem.url = item.fileUrlitem.uid = item.uid || new Date().getTime() + temp++;return item;});} else {this.fileList = [];return [];}},},methods:{// 上傳前校檢格式和大小handleBeforeUpload(file) {// 校檢文件類型if (this.fileType) {let fileExtension = "";if (file.name.lastIndexOf(".") > -1) {fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);}const isTypeOk = this.fileType.some((type) => {if (file.type.indexOf(type) > -1) return true;if (fileExtension && fileExtension.indexOf(type) > -1) return true;return false;});if (!isTypeOk) {this.$message.error(`文件格式不正確, 請上傳${this.fileType.join("/")}格式文件!`);return false;}}// 校檢文件大小if (this.fileSize) {const isLt = file.size / 1024 / 1024 < this.fileSize;if (!isLt) {this.$message.error(`上傳文件大小不能超過 ${this.fileSize} MB!`);return false;}}return true;},// 文件個數超出handleExceed(e) {if(this.limit == 1) {this.$message.error(`只能上傳一個文件,請先刪除原文件后重新上傳!`);} else {this.$message.error(`上傳文件數量不能超過 ${props.limit} 個!`);}},// 上傳失敗handleUploadError(err) {this.$message.error("上傳失敗, 請重試");},// 上傳成功回調handleUploadSuccess(res, file) {this.fileList.push({name:res.data.name, url:res.data.url, fileName:res.data.name, fileUrl:res.data.url})this.$message.success("上傳成功");this.$emit("input", this.fileList);},// 刪除文件handleDelete(index) {this.fileList.splice(index, 1);this.$emit("input", this.fileList);},// 獲取文件名稱getFileName(name) {if (name.lastIndexOf("/") > -1) {return name.slice(name.lastIndexOf("/") + 1).toLowerCase();} else {return "";}}},})Vue.component('vue-upload',demoComponent)
2、在html中使用,在html中引入上面的vueUpload.js自定義組件文件
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>測試</title><script src="https://unpkg.com/vue@2/dist/vue.js"></script><!-- 引入樣式 --><link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"><!-- 引入組件庫 --><script src="https://unpkg.com/element-ui/lib/index.js"></script><!-- 引入自定義上傳組件 --><script src="./vueUpload.js"></script>
</head>
<body><div id="app"><vue-upload v-model="fileList" :limit="1" :file-type="['doc','docx','pdf']" :file-size="50"></vue-upload> </div><script>var app = new Vue({el: '#app',data () {return {fileList:[{fileName:'測試.pdf',fileUrl:'http://www.baidu.com/img/bd_logo1.png'}],}},mounted () {},methods: {}})</script>
</body>
</html>
3、展示效果
總結:在html中使用vue創建自定義組件和在vue中創建自定義組件基本一樣,只不過寫在js里最后記得把自定義組件通過Vue.component('vue-upload',demoComponent),掛載到vue上,還有在html中標簽還有屬性名都不可以用駝峰命名,切記!!!!!,駝峰命名的單詞改用 ‘-’ 的寫法