問題描述
在最近的項目開發中遇到了這樣的一個問題,當我上傳了一個文件時,我將獲取到的文件名清空后,卻無法再次上傳相同的文件
<template> <div class="hello">   <input type="button" value="上傳文件" name="" id="" @click="updata">   <input type="file" style="display:none" @change="getFile" id="input-file">   <div v-if="fileName">    <p>上傳的文件名:{{fileName}}</p>    <button @click="delFile">清空文件</button>   </div> </div></template><script>import $ from 'n-zepto'export default { name: 'HelloWorld', data () {  return {   fileName: ''  } }, methods:{  updata(){ // 喚起change事件   $('#input-file').click()  },  getFile(e){ // change事件   this.doSomething()  },  doSomething(){ // do something   this.fileName = e.target.files[0].name  },  delFile(){   this.fileName=''  } }}</script>因為我只是將data中的屬性值清空而已,文件名沒有變當然會不出發change事件
解決辦法
目前網上有好多解決辦法,但基本上都無法在vue上使用,于是我想到了v-if
v-if 是“真正”的條件渲染,因為它會確保在切換過程中條件塊內的事件監聽器和子組件適當地被銷毀和重建。
于是在代碼中加入了一個小的開關,喚起change事件時就將他銷毀
事件結束時再將它重建,這樣問題就輕松的解決了
<template> <div class="hello">   <input type="button" value="上傳文件" name="" id="" @click="updata">   <input v-if="ishowFile" type="file" style="display:none" @change="getFile" id="input-file">   <div v-if="fileName">    <p>上傳的文件名:{{fileName}}</p>    <button @click="delFile">清空文件</button>   </div> </div></template><script>import $ from 'n-zepto'export default { name: 'HelloWorld', data () {  return {   fileName: '',   ishowFile: true,  } }, methods:{  updata(){ // 喚起change事件   $('#input-file').click()   this.ishowFile = false // 銷毀  },  getFile(e){ // change事件   this.doSomething()   this.ishowFile = false // 重建  },  doSomething(){ // do something   this.fileName = e.target.files[0].name  },  delFile(){   this.fileName=''  } }}</script>總結
以上所述是小編給大家介紹的vue項目中解決type=”file“ change事件只執行一次的問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對錯新站長站網站的支持!
新聞熱點
疑難解答
圖片精選