search
HomeWeb Front-endJS TutorialHow to implement import and export in vue + element-ui

How to implement import and export in vue + element-ui

Jun 19, 2018 am 10:11 AM
elementuiuivueExport

Element-UI is a desktop UI framework based on Vue.js 2.0 launched by the Ele.me front-end team. The corresponding framework for mobile phones is Mint UI. The following article mainly introduces you to the use of vue element- Friends who need information on how to implement concise import and export functions in UI can refer to it.

Preface

As we all know, ElementUI is a relatively complete UI library, but using it requires a bit of Vue foundation. Before starting the main text of this article, let's take a look at the installation method.

Install ElementUI module

cnpm install element-ui -S

Introduce into main.js

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

Global installation

Vue.use(ElementUI)

Remember to reinstall when we finish the installation Run, cnpm run dev , now you can use elementUI directly.

vue element-ui import and export function

1. Data display in the front-end backend management system generally uses tables, and the tables will involve Import and export;

2. Import is using the Upload upload component of element-ui;

<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. Export is using an object blob of file; get the data by calling the background interface, and then Use data to instantiate the blob, and use the href attribute of the a tag to link to the blob object

 export const downloadTemplate = function (scheduleType) {
  axios.get(&#39;/rest/schedule/template&#39;, {
   params: {
    "scheduleType": scheduleType
   },
   responseType: &#39;arraybuffer&#39;
  }).then((response) => {
   //创建一个blob对象,file的一种
   let blob = new Blob([response.data], { type: &#39;application/x-xls&#39; })
   let link = document.createElement(&#39;a&#39;)
   link.href = window.URL.createObjectURL(blob)
   //配置下载的文件名
   link.download = fileNames[scheduleType] + &#39;_&#39; + response.headers.datestr + &#39;.xls&#39;
   link.click()
  })
 }

4. Paste the complete code of the entire small demo, which can be used directly in the background development (vue file)

<template>
<p>
 <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>
 <p 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>
 </p>
 <!-- 导入 -->
 <el-dialog title="导入" :visible.sync="dialogImportVisible" :modal-append-to-body="false" :close-on-click-modal="false" class="dialog-import">
  <p :class="{&#39;import-content&#39;: importFlag === 1, &#39;hide-dialog&#39;: 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>
   <p slot="tip" class="el-upload__tip">只能上传excel文件</p>
  </el-upload>
  <p class="download-template">
   <a class="btn-download" @click="download">
   <i class="icon-download"></i>下载模板</a>
  </p>
  </p>
  <p :class="{&#39;import-failure&#39;: importFlag === 2, &#39;hide-dialog&#39;: importFlag !== 2}" >
  <p class="failure-tips">
   <i class="el-icon-warning"></i>导入失败</p>
  <p class="failure-reason">
   <h4 id="失败原因">失败原因</h4>
   <ul>
   <li v-for="(error,index) in errorResults" :key="index">第{{error.rowIdx + 1}}行,错误:{{error.column}},{{error.value}},{{error.errorInfo}}</li>
   </ul>
  </p>
  </p>
 </el-dialog>

 <!-- 导出 -->
</p>
</template>
<script>
import * as scheduleApi from &#39;@/api/schedule&#39;
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:&#39;www.baidu.com&#39;,//后台接口config.admin_url+&#39;rest/schedule/import/&#39;
  importHeaders:{
  enctype:&#39;multipart/form-data&#39;,
  cityCode:&#39;&#39;
  },
  name: &#39;import&#39;,
  fileList: [],
  withCredentials: true,
  processing: false,
  uploadTip:&#39;点击上传&#39;,
  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 = &#39;点击上传&#39;
  this.processing = false
  this.dialogImportVisible = true
 },
 outportData() {
  scheduleApi.downloadTemplate()
 },
 handlePreview(file) {
  //可以通过 file.response 拿到服务端返回数据
 },
 handleRemove(file, fileList) {
  //文件移除
 },
 beforeUpload(file){
  //上传前配置
  this.importHeaders.cityCode=&#39;上海&#39;//可以配置请求头
  let excelfileExtend = ".xls,.xlsx"//设置文件格式
  let fileExtend = file.name.substring(file.name.lastIndexOf(&#39;.&#39;)).toLowerCase();
  if (excelfileExtend.indexOf(fileExtend) <= -1) {
   this.$message.error(&#39;文件格式错误&#39;)
   return false
  }
  this.uploadTip = &#39;正在处理中...&#39;
  this.processing = true
 },
 //上传错误
 uploadFail(err, file, fileList) {
  this.uploadTip = &#39;点击上传&#39;
  this.processing = false
  this.$message.error(err)
 },
 //上传成功
 uploadSuccess(response, file, fileList) {
  this.uploadTip = &#39;点击上传&#39;
  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(&#39;导入成功&#39;)
  this.doSearch()
  }
 },
 //下载模板
 download() {
  //调用后台模板方法,和导出类似
  scheduleApi.downloadTemplate()
 },
 }
};
</script>
<style scoped>
.hide-dialog{
 display:none;
}
</style>

5.js file, calling interface

import axios from &#39;axios&#39;
// 下载模板
 export const downloadTemplate = function (scheduleType) {
  axios.get(&#39;/rest/schedule/template&#39;, {
   params: {
    "scheduleType": scheduleType
   },
   responseType: &#39;arraybuffer&#39;
  }).then((response) => {
   //创建一个blob对象,file的一种
   let blob = new Blob([response.data], { type: &#39;application/x-xls&#39; })
   let link = document.createElement(&#39;a&#39;)
   link.href = window.URL.createObjectURL(blob)
   link.download = fileNames[scheduleType] + &#39;_&#39; + response.headers.datestr + &#39;.xls&#39;
   link.click()
  })
 }

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement table paging in vue element

How to implement recording and playback recording functions in WeChat applet

Nuxt.js framework (detailed tutorial)

How to implement a rolling digital clock in JS CSS

How to achieve the centered floating effect of pictures in JS

How to use the laydate.js date plug-in in Angular4.0

In jQuery How to implement online customer service function

The above is the detailed content of How to implement import and export in vue + element-ui. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software