vant的uploader组件的交互是点击上传之后才会触发一系列回调函数,如果想要实现点击uploader的时候先出现弹框提示,选择了确定之后才进行文件上传这该怎么做到呢?
大致是,给uploader组件外面包裹一层元素,然后给组件设为禁用模式,当外层的元素状态改变时,就改变组件的disabled值,再使用vant提供的chooseFile通过 ref 可以获取到 Uploader 实例并调用实例的方法重新调起文件选择。
主要的步骤如下:
首先,我们可以在uploader组件外面包裹一层div
<span
@click="handleClick"
v-if="isconfirm"
class="message"
></span>
<van-uploader
v-model="fileList"
:after-read="afterRead"
:disabled="isconfirm"
ref="uploadImg"
/>
然后在data以及methods中进行定义
data() {
return {
fileList: [],
isconfirm: true
};
methods: {
handleClick() {
this.$dialog
.confirm({
message: "test,test,test"
})
.then(() => {
this.isconfirm = false;
this.$refs.uploadImg.chooseFile();
})
.catch(() => {
this.isconfirm = true;
});
},
}
看到这里要注意chooseFile这个方法支持的版本是v2.5.6以上的,如果出现了没有效果的话,先检查一下自己安装的版本是否是符合要求的。
检查之后,版本也符合要求,但是this.$refs.uploadImg.chooseFile()就是没有效果,这是怎么一回事呢?
原来跟浏览器执行机制event loop有关,每当执行到choosefile的时候,组件仍为禁用模式,无法调起,其实isconfirm状态还没有进行改变,所以调起文件选择看不见效果,可以使用一个setTimeout或者是vue中的this.$nextTick()进行解决。
setTimeout(() => {
this.$refs.uploadImg.chooseFile();
}, 0);
this.$nextTick(() => {
this.$refs.uploadImg.chooseFile();
});