Vue에서 파일 구성 요소를 캡슐화하고 업로드하는 단계에 대한 자세한 설명(코드 포함)

php中世界最好的语言
풀어 주다: 2018-05-03 15:58:43
원래의
3542명이 탐색했습니다.

이번에는 Vue에서 업로드 파일 컴포넌트를 패키징하는 단계(코드 포함)에 대해 자세히 설명했습니다. Vue에서 업로드 파일 컴포넌트를 패키징할 때 주의 사항은 무엇입니까? .

1. 이전에 발생한 문제

기존 UI 프레임워크를 사용하여 구현하는 과정에서 알 수 없는 이유로 항상 설명할 수 없는 버그가 발생합니다. 예를 들어 특정 업로드 구성 요소를 사용하는 경우 (:multiple="false")로 명확하게 표시되지만 실제로는 여러 파일을 선택할 수 있으며 업로드 시 여러 파일이 계속 전송됩니다. (:file-list="fileList"가 추가됨) ") 속성을 사용하여 업로드 목록을 수동으로 제어하려는 경우 업로드 이벤트 this.refs.[upload (컴포넌트 참조)].submit()이 작동하지 않으며 실행할 수 없습니다. 전송됩니다. 간단히 말해서 함수를 사용하고 있는데 인터페이스 자체를 다시 작성해야 하는데, 굳이 사용하면 프로젝트에 불필요한 로직과 스타일 코드가 많이 추가될 것입니다. ...

저는 이전에 프로젝트에 Vue를 사용했습니다. 뷰 프레임워크에는 팀 내 보완 요소로 element-ui, zp-ui, iview가 포함되어 있습니다. 프레임워크는 사용하기 쉽지만 자신의 프로젝트에 사용하지 못하는 경우가 많습니다. 특히 우리 디자인 소녀가 만든 인터페이스는 기존 프레임워크와 매우 다르며, 소스 코드를 변경하는 것은 비효율적이며 쉽게 알 수 없는 버그로 이어질 수 있습니다. 그래서 시간을 내어 이 업로드 구성 요소를 캡슐화합니다.

2. 코드 및 소개

상위 컴포넌트

<template>
 <p class="content">
 <label for="my-upload">
  <span>上传</span>
 </label>
  <my-upload
   ref="myUpload"
   :file-list="fileList"
   action="/uploadPicture"
   :data="param"
   :on-change="onChange"
   :on-progress="uploadProgress"
   :on-success="uploadSuccess"
   :on-failed="uploadFailed"
   multiple
   :limit="5"
   :on-finished="onFinished">
  </my-upload>
  <button @click="upload" class="btn btn-xs btn-primary">Upload</button>
 </p>
</template>
<script>
import myUpload from './components/my-upload'
export default {
 name: 'test',
 data(){
  return {
  fileList: [],//上传文件列表,无论单选还是支持多选,文件都以列表格式保存
  param: {param1: '', param2: '' },//携带参数列表
  }
 },
 methods: {
  onChange(fileList){//监听文件变化,增减文件时都会被子组件调用
  this.fileList = [...fileList];
  },
  uploadSuccess(index, response){//某个文件上传成功都会执行该方法,index代表列表中第index个文件
  console.log(index, response);
  },
  upload(){//触发子组件的上传方法
  this.$refs.myUpload.submit();
  },
  removeFile(index){//移除某文件
  this.$refs.myUpload.remove(index);
  },
  uploadProgress(index, progress){//上传进度,上传时会不断被触发,需要进度指示时会很有用
  const{ percent } = progress;
  console.log(index, percent);
  },
  uploadFailed(index, err){//某文件上传失败会执行,index代表列表中第index个文件
  console.log(index, err);
  },
  onFinished(result){//所有文件上传完毕后(无论成败)执行,result: { success: 成功数目, failed: 失败数目 }
  console.log(result);
  }
 },
 components: {
  myUpload
 }
}
</script>
로그인 후 복사

상위 컴포넌트는 비즈니스 관련 로직을 처리하는데, 업로드 결과를 표시할 때 해당 값을 직접 연산할 수 있도록 인터페이스를 용이하게 하기 위해 인덱스 매개변수를 특별히 추가한 것은 아닙니다. 모든 방법이 필요하며 필요에 따라 사용해야 합니다.

하위 구성 요소

<template>
<p>
 <input style="display:none" @change="addFile" :multiple="multiple" type="file" :name="name" id="my-upload"/>
</p>
</template>
로그인 후 복사

파일 업로드, html 부분은 단지 태그 쌍일 뿐이고 복잡성이 마음에 들지 않습니다

<script>
export default {
 name: 'my-upload',
 props: {
 name: String,
 action: {
  type: String,
  required: true
 },
 fileList: {
  type: Array,
  default: []
 },
 data: Object,
 multiple: Boolean,
 limit: Number,
 onChange: Function,
 onBefore: Function,
 onProgress: Function,
 onSuccess: Function,
 onFailed: Function,
 onFinished: Function
 },
 methods: {}//下文主要是methods的介绍,此处先省略
}
</script>
로그인 후 복사

이것은 상위 구성 요소에서 하위 구성 요소로 전달되어야 하는 속성 값을 정의합니다. 메소드는 여기서도 속성으로 전달됩니다. 모두 가능합니다.

내가 작성한 구성 요소는 인기 있는 프레임워크에서 출시된 구성 요소만큼 완전하고 포괄적이지 않습니다. 또한 처음에 언급한 바인딩된 파일 목록을 업로드할 수 없는 문제를 해결하기 위해 최선을 다하고 싶습니다. 자세가 잘못되었습니다.) 발생한 이 문제를 해결하기 위해 파일 목록에 대한 절대적인 제어권을 갖고 싶습니다. 파일 목록도 부모가 전달해야 하는 속성으로 사용됩니다. 요소. (상위 컴포넌트의 속성명은 "-"로 연결되는데, 이는 하위 컴포넌트 prop의 Camel Case 명명에 해당함)

3. 주요 업로드 기능

methods: {
  addFile, remove, submit, checkIfCanUpload
}
로그인 후 복사

총 4가지 메소드가 있습니다. 메소드, 파일 추가, 파일 제거, 제출, 감지(업로드 전 검사)에 대해 아래에서 하나씩 설명하겠습니다.

1. 파일 추가

addFile({target: {files}}){//input标签触发onchange事件时,将文件加入待上传列表
 for(let i = 0, l = files.length; i < l; i++){
 files[i].url = URL.createObjectURL(files[i]);//创建blob地址,不然图片怎么展示?
 files[i].status = &#39;ready&#39;;//开始想给文件一个字段表示上传进行的步骤的,后面好像也没去用......
 }
 let fileList = [...this.fileList];
 if(this.multiple){//多选时,文件全部压如列表末尾
 fileList = [...fileList, ...files];
 let l = fileList.length;
 let limit = this.limit;
 if(limit && typeof limit === "number" && Math.ceil(limit) > 0 && l > limit){//有数目限制时,取后面limit个文件
  limit = Math.ceil(limit);
//  limit = limit > 10 ? 10 : limit;
  fileList = fileList.slice(l - limit);
 }
 }else{//单选时,只取最后一个文件。注意这里没写成fileList = files;是因为files本身就有多个元素(比如选择文件时一下子框了一堆)时,也只要一个
 fileList = [files[0]];
 }
 this.onChange(fileList);//调用父组件方法,将列表缓存到上一级data中的fileList属性
 },
로그인 후 복사

2. 파일 제거

이것은 간단합니다. 파일을 포크하면 인덱스만 전달하면 됩니다.

remove(index){
 let fileList = [...this.fileList];
 if(fileList.length){
 fileList.splice(index, 1);
 this.onChange(fileList);
 }
},
로그인 후 복사

3. 제출 업로드

여기에서는 가져오기와 기본 메서드라는 두 가지 방법이 사용됩니다. 가져오기는 업로드 진행률 가져오기를 지원하지 않으므로 진행률 표시줄이 필요하지 않거나 진행 상황을 직접 시뮬레이션하거나 XMLHttpRequest 개체가 지원하지 않는 경우 가져오기 요청 업로드 로직이 더 간단해집니다

submit(){
 if(this.checkIfCanUpload()){
 if(this.onProgress && typeof XMLHttpRequest !== 'undefined')
  this.xhrSubmit();
 else
  this.fetchSubmit();
 }
},
로그인 후 복사

4. 두 가지 업로드 로직 세트를 기반으로 xhrSubmit 및 fetchSubmit 두 가지 메소드가 여기에 캡슐화되어 있습니다

fetchSubmit

fetchSubmit(){
 let keys = Object.keys(this.data), values = Object.values(this.data), action = this.action;
 const promises = this.fileList.map(each => {
 each.status = "uploading";
 let data = new FormData();
 data.append(this.name || 'file', each);
 keys.forEach((one, index) => data.append(one, values[index]));
 return fetch(action, {
  method: 'POST',
  headers: {
   "Content-Type" : "application/x-www-form-urlencoded"
  },
  body: data
 }).then(res => res.text()).then(res => JSON.parse(res));//这里res.text()是根据返回值类型使用的,应该视情况而定
 });
 Promise.all(promises).then(resArray => {//多线程同时开始,如果并发数有限制,可以使用同步的方式一个一个传,这里不再赘述。
 let success = 0, failed = 0;
 resArray.forEach((res, index) => {
  if(res.code == 1){
  success++;         //统计上传成功的个数,由索引可以知道哪些成功了
  this.onSuccess(index, res);
  }else if(res.code == 520){   //约定失败的返回值是520
  failed++;         //统计上传失败的个数,由索引可以知道哪些失败了
  this.onFailed(index, res);
  }
 });
 return { success, failed };   //上传结束,将结果传递到下文
 }).then(this.onFinished);      //把上传总结果返回
},
로그인 후 복사

xhrSubmit

xhrSubmit(){
  const _this = this;
 let options = this.fileList.map((rawFile, index) => ({
 file: rawFile,
 data: _this.data,
    filename: _this.name || "file",
    action: _this.action,
    onProgress(e){
     _this.onProgress(index, e);//闭包,将index存住
    },
    onSuccess(res){
     _this.onSuccess(index, res);
    },
    onError(err){
     _this.onFailed(index, err);
    }
  }));
 let l = this.fileList.length;
 let send = async options => {
 for(let i = 0; i < l; i++){
  await _this.sendRequest(options[i]);//这里用了个异步方法,按次序执行this.sendRequest方法,参数为文件列表包装的每个对象,this.sendRequest下面紧接着介绍
 }
 };
 send(options);
},
로그인 후 복사

이것은 업로드 소스를 기반으로 합니다. code of element-ui

sendRequest(option){
 const _this = this;
  upload(option);
 function getError(action, option, xhr) {
  var msg = void 0;
  if (xhr.response) {
   msg = xhr.status + &#39; &#39; + (xhr.response.error || xhr.response);
  } else if (xhr.responseText) {
   msg = xhr.status + &#39; &#39; + xhr.responseText;
  } else {
   msg = &#39;fail to post &#39; + action + &#39; &#39; + xhr.status;
  }
  var err = new Error(msg);
  err.status = xhr.status;
  err.method = &#39;post&#39;;
  err.url = action;
  return err;
 }
 function getBody(xhr) {
  var text = xhr.responseText || xhr.response;
  if (!text) {
   return text;
  }
  try {
   return JSON.parse(text);
  } catch (e) {
   return text;
  }
 }
 function upload(option) {
  if (typeof XMLHttpRequest === &#39;undefined&#39;) {
   return;
  }
  var xhr = new XMLHttpRequest();
  var action = option.action;
  if (xhr.upload) {
   xhr.upload.onprogress = function progress(e) {
    if (e.total > 0) {
     e.percent = e.loaded / e.total * 100;
    }
    option.onProgress(e);
   };
  }
  var formData = new FormData();
  if (option.data) {
   Object.keys(option.data).map(function (key) {
    formData.append(key, option.data[key]);
   });
  }
  formData.append(option.filename, option.file);
  xhr.onerror = function error(e) {
   option.onError(e);
  };
  xhr.onload = function onload() {
   if (xhr.status < 200 || xhr.status >= 300) {
    return option.onError(getError(action, option, xhr));
   }
   option.onSuccess(getBody(xhr));
  };
  xhr.open('post', action, true);
  if (option.withCredentials && 'withCredentials' in xhr) {
   xhr.withCredentials = true;
  }
  var headers = option.headers || {};
  for (var item in headers) {
   if (headers.hasOwnProperty(item) && headers[item] !== null) {
    xhr.setRequestHeader(item, headers[item]);
   }
  }
  xhr.send(formData);
  return xhr;
 }
}
로그인 후 복사

요청 전에 마지막으로 확인을 추가하세요

checkIfCanUpload(){
 return this.fileList.length ? (this.onBefore && this.onBefore() || !this.onBefore) : false;
},
로그인 후 복사

부모 컴포넌트가 onBefore 메소드를 정의하고 false를 반환하거나 파일 목록이 비어 있으면 요청이 전송되지 않습니다.

코드 부분이 완료되었습니다. on-progress 속성이 존재하고 XMLHttpRequest 객체에 액세스할 수 있는 한 요청은 기본 방식으로 전송됩니다. 진행 상황은 표시되지 않습니다).

이 기사의 사례를 읽은 후 방법을 마스터했다고 생각합니다. 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사를 주목하세요!

추천 도서:

JS 이벤트 위임 사용에 대한 자세한 설명

Bootstrap에서 WebUploader를 사용하는 단계에 대한 자세한 설명

위 내용은 Vue에서 파일 구성 요소를 캡슐화하고 업로드하는 단계에 대한 자세한 설명(코드 포함)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!