在项目中使用iview
中upload
组件的自定义上传列表
时,根据项目的应用场景,我需要动态设置默认的显示列表,但是在我手动修改defaultList
的值后,发现页面并无任何变化,并且图片上传成功后,文件列表也不再显示所上传的文件,我尝试打印了console.log(this.$refs.upload)
,结果中的defaultFileList和fileList
都为我设置的内容,但是单独打印了console.log(this.$refs.upload.fileList)
,发现结果显示的还是修改前的内容,这就奇了怪了??????
解决办法
<!-- 在这里完全按照官方文档的来 -->
<template>
<div class="demo-upload-list" v-for="item in uploadList">
<template v-if="item.status === 'finished'">
<img :src="item.url">
<div class="demo-upload-list-cover">
<Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon>
<Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
</div>
</template>
<template v-else>
<Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
</template>
</div>
<Upload
ref="upload"
:show-upload-list="false"
:default-file-list="defaultList"
:on-success="handleSuccess"
:format="['jpg','jpeg','png']"
:max-size="2048"
:on-format-error="handleFormatError"
:on-exceeded-size="handleMaxSize"
:before-upload="handleBeforeUpload"
multiple
type="drag"
action="//jsonplaceholder.typicode.com/posts/"
style="display: inline-block;width:58px;">
<div style="width: 58px;height:58px;line-height: 58px;">
<Icon type="ios-camera" size="20"></Icon>
</div>
</Upload>
<Modal title="View Image" v-model="visible">
<img :src="'https://o5wwk8baw.qnssl.com/' + imgName + '/large'" v-if="visible" style="width: 100%">
</Modal>
</template>
<script>
export default {
data () {
return {
defaultList: [
{
'name': 'a42bdcc1178e62b4694c830f028db5c0',
'url': 'https://o5wwk8baw.qnssl.com/a42bdcc1178e62b4694c830f028db5c0/avatar'
},
{
'name': 'bc7521e033abdd1e92222d733590f104',
'url': 'https://o5wwk8baw.qnssl.com/bc7521e033abdd1e92222d733590f104/avatar'
}
],
imgName: '',
visible: false,
uploadList: []
}
},
methods: {
// ...
},
mounted () {
let aa = {
'name': 'a42bdcc1178e62b4694c830f028db5c0',
'url': 'https://o5wwk8baw.qnssl.com/a42bdcc1178e62b4694c830f028db5c0/avatar'
}
// ********************重点来了************************
// *********第一种方法***********
this.defaultList.push(aa)
// 必须先对defaultList赋值,然后在$nextTick()中在对uploadList赋值
// 不放在$nextTick()中,那么fileList拿到的是defaultList的最初的值,而不是修改后的值
this.$nextTick(()=>{
this.uploadList = this.$refs.upload.fileList;
})
// **********************第二种方法**********************************
// this.uploadList = this.$refs.upload.fileList;
},
beforeMount () {
// **********************第二种方法**********************************
/*
let aa = {
'name': 'a42bdcc1178e62b4694c830f028db5c0',
'url': 'https://o5wwk8baw.qnssl.com/a42bdcc1178e62b4694c830f028db5c0/avatar'
}
this.defaultList.push(aa)
*/
}
}
</script>
总之,要先设置
defaultList
,待DOM
更新后在将fileList
赋值给uploadList