English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

vue + element-ui에서 간단한 임포트 및 업로드 기능 구현

서론

众所周知,ElementUI는 상대적으로 완벽한 UI 라이브러리입니다만, 사용하기 위해서는 Vue의 기본적인 이해가 필요합니다. 본문의 본문을 시작하기 전에, 먼저 설치 방법을 확인해 보겠습니다.

ElementUI 모듈 설치

cnpm install element-ui -S

main.js에서 입력

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'

전체 설치

Vue.use(ElementUI)

설치가 완료되면 다시 실행해야 합니다. cnpm run dev, 지금은 직접 elementUI를 사용할 수 있습니다.

vue + element-ui 내보내기/내보내기 기능

1. 프론트엔드 백엔드 관리 시스템에서 데이터 표시는 대부분 테이블을 사용하며, 테이블은 내보내기와 내보내기에 관련됩니다;

2. 내보내기는 element-ui의 Upload 업로드 컴포넌트;

<el-upload class="upload-demo"
  :action="importUrl"//업로드 경로
  :name ="name"//업로드 파일 필드 이름
  :headers="importHeaders"//요청 헤더 형식
  :on-preview="handlePreview"//서버에서 반환된 데이터를 file.response 통해 가져올 수 있습니다.
  :on-remove="handleRemove"//파일 제거
  :before-upload="beforeUpload"//업로드 전 설정
  :on-error="uploadFail"//업로드 오류
  :on-success="uploadSuccess"//업로드 성공
  :file-list="fileList"//업로드 파일 목록
  :with-credentials="withCredentials">//cookie 정보 전송 지원 여부
</el-upload>

3. 내보내기는 file의 객체 blob을 사용하여, 백엔드 인터페이스를 호출하여 데이터를 받아온 후, 데이터를 사용하여 blob을 인스턴스화하고, a 태그의 href 속성을 blob 객체로 링크합니다

 export const downloadTemplate = function (scheduleType) {
  axios.get('/rest/schedule/template', {
   params: {
    "scheduleType": scheduleType
   ,
   responseType: 'arraybuffer'
  }).then((response) => {
   //blob 객체를 생성하다, file의 하나
   let blob = new Blob([response.data], { type: 'application/x-xls' })
   let link = document.createElement('a')
   link.href = window.URL.createObjectURL(blob)
   //다운로드 파일 이름 설정
   link.download = fileNames[scheduleType] + '_' + response.headers.datestr + '.xls'
   link.click()
  }
 }

4. 전체 소모델의 코드를 붙여넣어, 백엔드 개발에서 직접 사용할 수 있습니다(vue 파일)

<template>
<div>
 <el-table
 ref="multipleTable"
 :data="tableData3"
 tooltip-effect="dark"
 border
 style="width: 80%"
 @selection-change="handleSelectionChange">
 <el-table-column
  type="selection"
  width="55">
 </el-table-column>
 <el-table-column
  label="날짜"
  width="120">
  <template slot-scope="scope">{{ scope.row.date }}</template>
 </el-table-column>
 <el-table-column
  prop="name"
  label="이름"
  width="120">
 </el-table-column>
 <el-table-column
  prop="address"
  label="주소"
  show-overflow-tooltip>
 </el-table-column>
 </el-table>
 <div style="margin-top: 20px">
 <el-button @click="toggleSelection([tableData3[1], tableData3[2])">두 번째, 세 번째 행의 선택 상태 전환</el-button>
 <el-button @click="toggleSelection()">취소 선택</el-button>
 <el-button type="primary" @click="importData">导入</el-button>
 <el-button type="primary" @click="outportData">导出</el-button>
 </div>
 <!-- 导入 -->
 <el-dialog title="[1#]" :visible.sync="dialogImportVisible" :modal-append-to-body="false" :close-on-click-modal="false" class="dialog-import">
  <div :class="{'import-content': importFlag === 1, 'hide-dialog': importFlag !== 1}">
  <el-upload class="upload-demo"
  :action="importUrl"
  :name ="name"
  :headers="importHeaders"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
  :before-upload="beforeUpload"
  :on-error="uploadFail"
  :on-success="uploadSuccess"
  :file-list="fileList"
  :with-credentials="withCredentials">
  <!-- cookie 정보를 전송할지 지원합니다 -->
   <el-button size="small" type="primary" :disabled="processing">{{uploadTip}}</el-button>
   <div slot="tip" class="el-upload__tip">excel 파일만 업로드할 수 있습니다</div>
  </el-upload>
  <div class="download-template">
   <a class="btn-download" @click="download">
   <i class="icon-download"></i>템플릿 다운로드</a>
  </div>
  </div>
  <div :class="{'import-failure': importFlag === 2, 'hide-dialog': importFlag !== 2" >
  <div class="failure-tips">
   <i class="el-icon-warning"></i>데이터 가져오기 실패</div>
  <div class="failure-reason">
   <h4>실패 이유</h4>
   <ul>
   <li v-for="(error,index) in errorResults" :key="index">第{{error.rowIdx} + 1}} 행, 오류: {{error.column}}, {{error.value}}, {{error.errorInfo}}</li>
   </ul>
  </div>
  </div>
 </el-dialog>
 <!-- 내보내기 -->
</div>
</template>
<script>
import * as scheduleApi from '@/api/schedule'
export default {
 data() {
 return {
  tableData3: [
  {
   date: "2016-05-03"
   name: "王小虎",
   address: "상하이시 푸단구 진사정로" 1518 뭉치
  ,
  {
   date: "2016-05-02"
   name: "王小虎",
   address: "상하이시 푸단구 진사정로" 1518 뭉치
  ,
  {
   date: "2016-05-04"
   name: "王小虎",
   address: "상하이시 푸단구 진사정로" 1518 뭉치
  ,
  {
   date: "2016-05-01"
   name: "王小虎",
   address: "상하이시 푸단구 진사정로" 1518 뭉치
  ,
  {
   date: "2016-05-08"
   name: "王小虎",
   address: "상하이시 푸단구 진사정로" 1518 뭉치
  ,
  {
   date: "2016-05-06"
   name: "王小虎",
   address: "상하이시 푸단구 진사정로" 1518 뭉치
  ,
  {
   date: "2016-05-07"
   name: "王小虎",
   address: "상하이시 푸단구 진사정로" 1518 뭉치
  }
  ],
  multipleSelection: [],
  importUrl:'www.baidu.com',//백엔드 인터페이스 config.admin_url+'rest/schedule/import/'
  importHeaders:{
  enctype:'multipart/form-data',
  cityCode: ''
  ,
  name: 'import',
  fileList: [],
  withCredentials: true,
  processing: false,
  uploadTip: '업로드 클릭',
  importFlag:1,
  dialogImportVisible: false,
  errorResults:[]
 };
 ,
 methods: {
 toggleSelection(rows) {
  if (rows) {
  rows.forEach(row => {
   this.$refs.multipleTable.toggleRowSelection(row);
  });
  } else {
  this.$refs.multipleTable.clearSelection();
  }
 ,
 handleSelectionChange(val) {
  //체크박스 선택 복원 함수, val이 전체 행 데이터를 반환
  this.multipleSelection = val;
 ,
 importData() {
  this.importFlag = 1
  this.fileList = []
  this.uploadTip = '업로드 클릭'
  this.processing = false
  this.dialogImportVisible = true
 ,
 outportData() {
  scheduleApi.downloadTemplate()
 ,
 handlePreview(file) {
  //서버에서 반환된 데이터를 file.response 통해 가져올 수 있습니다.
 ,
 handleRemove(file, fileList) {
  //파일 제거
 ,
 beforeUpload(file){
  //업로드 전 설정
  this.importHeaders.cityCode='상해'//요청 헤더 설정 가능
  let excelfileExtend = ".xls,.xlsx"//파일 형식 설정
  let fileExtend = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  if (excelfileExtend.indexOf(fileExtend) <= -1) {
   this.$message.error('파일 형식 오류')
   return false
  }
  this.uploadTip = '처리 중...'
  this.processing = true
 ,
 //업로드 오류
 uploadFail(err, file, fileList) {
  this.uploadTip = '업로드 클릭'
  this.processing = false
  this.$message.error(err)
 ,
 //업로드 성공
 uploadSuccess(response, file, fileList) {
  this.uploadTip = '업로드 클릭'
  this.processing = false
  if (response.status === -1) {
  this.errorResults = response.data
  if (this.errorResults) {
   this.importFlag = 2
  } else {
   this.dialogImportVisible = false
   this.$message.error(response.errorMsg)
  }
  } else {
  this.importFlag = 3
  this.dialogImportVisible = false
  this.$message.info('импорт успешен')
  this.doSearch()
  }
 ,
 //템플릿 다운로드
 download() {
  //백엔드 템플릿 메서드 호출, 내보내기와 유사
  scheduleApi.downloadTemplate()
 ,
 }
};
</script>
<style scoped>
.hide-dialog{
 display:none;
}
</style>

5.js 파일, 인터페이스 호출

import axios from 'axios'
// 템플릿 다운로드
 export const downloadTemplate = function (scheduleType) {
  axios.get('/rest/schedule/template', {
   params: {
    "scheduleType": scheduleType
   ,
   responseType: 'arraybuffer'
  }).then((response) => {
   //blob 객체를 생성하다, file의 하나
   let blob = new Blob([response.data], { type: 'application/x-xls' })
   let link = document.createElement('a')
   link.href = window.URL.createObjectURL(blob)
   link.download = fileNames[scheduleType] + '_' + response.headers.datestr + '.xls'
   link.click()
  }
 }

결론

이 문서의 모든 내용이 끝납니다. 이 문서의 내용이 여러분의 학습이나 업무에 도움이 되길 바랍니다. 의문이 있으시면 댓글을 통해 교류해 주시기 바랍니다. 감사합니다. 나대본 교본에 대한 지원에 감사합니다.

성명서: 이 문서의 내용은 인터넷에서 가져왔으며, 저작권자는 모두입니다. 내용은 인터넷 사용자가 자발적으로 기여하고 업로드한 것이며, 이 사이트는 소유권을 가지지 않으며, 인공적인 편집을 하지 않았으며, 관련 법적 책임도 부담하지 않습니다. 저작권 침해가 의심되는 내용이 있으시면, notice#w로 이메일을 보내 주시기 바랍니다.3codebox.com(보내실 때, #을 @으로 변경하시기 바랍니다. 신고를 하시고, 관련 증거를 제공하시면, 실제로 확인되면, 이 사이트는 즉시 저작권 침해 내용을 삭제할 것입니다.

좋아하는 것