欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

解決vue項(xiàng)目中type=”file“ change事件只執(zhí)行一次的問題

 更新時(shí)間:2018年05月16日 08:33:38   作者:七尚  
這篇文章主要介紹了vue項(xiàng)目中解決type=”file“ change事件只執(zhí)行一次的問題,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下

問題描述

在最近的項(xiàng)目開發(fā)中遇到了這樣的一個(gè)問題,當(dāng)我上傳了一個(gè)文件時(shí),我將獲取到的文件名清空后,卻無法再次上傳相同的文件

<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>

因?yàn)槲抑皇菍ata中的屬性值清空而已,文件名沒有變當(dāng)然會(huì)不出發(fā)change事件

解決辦法

目前網(wǎng)上有好多解決辦法,但基本上都無法在vue上使用,于是我想到了v-if

v-if 是“真正”的條件渲染,因?yàn)樗鼤?huì)確保在切換過程中條件塊內(nèi)的事件監(jiān)聽器和子組件適當(dāng)?shù)乇讳N毀和重建。

于是在代碼中加入了一個(gè)小的開關(guān),喚起change事件時(shí)就將他銷毀

事件結(jié)束時(shí)再將它重建,這樣問題就輕松的解決了

<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>

總結(jié)

以上所述是小編給大家介紹的vue項(xiàng)目中解決type=”file“ change事件只執(zhí)行一次的問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評論