vue file upload+ref 範例(正常版+for loop)

by cactus77kiki

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>

<div id="app">    
  請輸入名稱:<input v-model="sname">
  <h2>#ref example 1</h2>
  <button type="button" v-on:click="trigger">選取檔案</button><br/>  
  <input type="file" ref="fileInput" v-on:change="uploadfile($event)" style="display:none"/>
  <br/>
  <h2>#ref example 2</h2>
  <button type="button" v-on:click="addbtn">新增一筆</button><hr/>
  <div v-for="(row,index) in rows">
    <button type="button" v-on:click="trigopen('fileinput' + row.id)">上傳</button>
    <input type="text" v-model="row.id" style="width:30px;">
    <input type="text" v-model="row.filename" style="width:100px;">
    <input type="text" v-model="row.remark" style="width:80px;">
    <input type="file" v-bind:ref="'fileinput' + row.id" style="display:none" v-on:click="resetUpload('fileinput'+ row.id)" v-on:change="goUpload($event,index)">
    <br/>
  </div>
</div>

JavaScript

var app = new Vue({
  el: '#app',
  data: {    
    sname: "",
    rows: [],
    inputs:{
      id:'',
      filename:'',
      remark:''
    }
  },
  methods: {
  //開啟上傳
  	trigger () {
      if(this.sname.length == 0){
        alert('請輸入名稱!');
      }else{      
      	this.$refs.fileInput.click();
      }      	    	
    },
    //開啟上傳
    uploadfile(event){
    	console.log(event.target.files);    
    },
    //動態新增
    addbtn(){
    	var arry = [];
      if(this.rows.length>0){
        //for (var i = 0; i < this.rows.length; i++)
        //	arry.push(this.rows[i]);
        arry = JSON.parse(JSON.stringify(this.rows));
      	this.inputs.id = this.rows.length+1;      	
      }else{
      	this.inputs.id = 1;      	
      } 
      arry.push(this.inputs);      	
      this.rows = JSON.parse(JSON.stringify(arry));
    },
    //開啟'上傳'
    trigopen(ref){
    	if(this.sname.length == 0){
        alert('請輸入名稱!');
      }else{            	        
        console.log(this.$refs[ref]);         
        this.$refs[ref][0].click();                
      }
    },
    //重設
    resetUpload(ref){
    	this.$refs[ref][0].value = "";   
    },
    //上傳
    goUpload(event, index){
    	var filer = event.target.files;
      if (filer) {
      	if (chkContainChJpn(filer[0].name)) {                    
        	alert("檔名含有中文!!");
          return false;
        } else {
        	//ajax上傳
          this.rows[index].filename = filer[0].name;
        }           
      }
    }
  }
})
//檢核是否含有中文
function chkContainChJpn(param){
	return param.search(RegExp("[一-" + String.fromCharCode(40869) + "]")) > -1;
}