1、封装子组件
<template>
<div class="app-container" style="padding: 8px;">
<el-upload
ref="child"
class="upload-demo"
drag
:action="fileUploadApi"
:data="params"
:headers="headers"
:on-remove="handleRemove"
:show-file-list="true"
:on-success="handleFileSuccess"
:before-upload="beforeFileUpload"
multiple
>
<i class="el-icon-upload" />
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div> -->
</el-upload>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
export default {
data() {
return {
headers: { 'Authorization': getToken() },
params: { name: '' },
fileList: []
}
},
computed: {
...mapGetters([
'fileUploadApi'
])
},
methods: {
//清空已上传的文件记录
clearFiles() {
this.$refs.child.clearFiles()
},
//清空已上传的文件,并重新赋值给父组件
handleRemove(file, fileList) {
var _this = this
if (_this.fileList.indexOf(file) !== -1) {
_this.fileList.reduce(file)
}
_this.$emit('name', _this.fileList)
},
//上传携带的参数name
beforeFileUpload(file) {
this.params.name = file.name
},
//图片转换成base64
imageToBase64(file) {
var _this = this
var reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => {
_this.$emit('url', reader.result)
_this.$emit('name', file.name)
}
reader.onerror = function(error) {
console.log('Error: ', error)
}
},
handleFileSuccess(response, file, fileList) {
this.fileList = fileList
this.imageToBase64(file.raw)
},
// 监听上传失败
handleError(e, file, fileList) {
const msg = JSON.parse(e.message)
this.$notify({
title: msg.message,
type: 'error',
duration: 2500
})
this.loading = false
}
}
}
</script>
<style scoped>
</style>
2.父组件引用
<fileUpload ref="child" v-model="form.wordPathList" style="width: 270px;" @url="getUrl" @name="getFileName" />
import fileUpload from '@/components/FileUpload'
components: {fileUpload },
//关闭dialog弹窗的同时清空子组件文件显示记录
closeDialog() {
//调用子组件方法前要在子组件设置@ref="child".同样父组件也设置。
this.$refs.child.clearFiles()
},
//获取子组件的文件列表内容
getUrl(data) {
this.crud.form.wordPathList.push(data)
},
//获取子组件的文件名称列表内容
getFileName(data) {
this.crud.form.wordNameList.push(data)
},
3.父组件给子组件某属性赋值
父组件设置 :url="xxx" 自定义属性名称及值。
<imgUpload v-model="form.frontOfIdCard" :url="form.frontOfIdCard" style="width: 270px;" />
然后在子组件设置属性值。
props: ['url'],
//如果要动态显示其值,则。
watch: {
url: function(newVal, oldVal) {
this.imageUrl = newVal
}
},