vue3點擊按鈕下載文件功能的代碼實現
更新時間:2024年01月02日 09:40:09 作者:梔椩
在寫vue項目時,有個需求是點擊表格中某一行的下載按鈕,然后開始下載這一行對應的文件,所以本文小編給大家介紹了使用vue3實現點擊按鈕下載文件功能,文中有詳細的代碼示例供大家參考,需要的朋友可以參考下
VUE3實現點擊按鈕下載文件功能
在寫vue項目時,有個需求是點擊表格中某一行的下載按鈕,然后開始下載這一行對應的文件,效果如下:
表格每行的最右側的藍色按鈕就是點擊下載,這里涉及到原生的JavaScript寫法,長期在寫vue項目,原生的寫法都很陌生了,記錄一下
先上組件的原始代碼:
<template> <BreadCrumb ref="breadCrumb" :item="item"></BreadCrumb> <div class="pane-content"> <div class="pane-top"> <div class="module-common-header"> <div class="button-wrapped"> <el-upload v-model:file-list="fileList" class="upload-demo" multiple :on-exceed="handleExceed" action="http://127.0.0.1:3088/api/files/uploadFile" :on-success="handleSuccess" :show-file-list="false"> <el-button type="primary">上傳文件</el-button> </el-upload> </div> </div> <div class="module-common-table"> <el-table :data="tableData" border style="width: 100%"> <el-table-column type="index" width="50"></el-table-column> <el-table-column show-overflow-tooltip v-for="(item, index) in tableLabel" :key="index" :prop="item.prop" :label="item.label" /> <el-table-column fixed="right" label="操作"> <template #default="scope"> <el-button type="primary" size="small" @click="downloadFile(scope.row)">下載文件</el-button> <el-popconfirm title="確定刪除該文件嗎?" confirm-button-text="是" cancel-button-text="否" @confirm="deleteFile(scope.row)"> <template #reference> <el-button type="danger" size="small">刪除文件</el-button> </template> </el-popconfirm> </template> </el-table-column> </el-table> </div> </div> <div class="table-footer"> <el-pagination :page-size="10" :pager-count="5" layout="prev, pager, next" :total="filesLength" :current-page="paginationData.currentPage" @current-change="currentPageChange" /> </div> </div> </template> <script setup> import { ref, onMounted } from 'vue' import { getFilesLengthAPI, returnFileListDataAPI, bindFileAndUserAPI, deleteFileAPI, updateDownloadTimesAPI, } from '@/apis/files' const item = ref({ first: '合同管理', }) const tableData = ref([]) const tableLabel = [ { prop: 'file_name', label: '合同名' }, { prop: 'file_size', label: '合同文件大小' }, { prop: 'upload_person', label: '上傳人' }, { prop: 'download_number', label: '下載次數' }, { prop: 'upload_time', label: '上傳時間' }, // { prop: 'message_content', label: '消息內容' }, ] const fileList = ref([]) // 上傳成功之后的回調函數 const handleSuccess = async (response, uploadFile, uploadFiles) => { if (response.status == 0) { const name = JSON.parse(localStorage.user).userInfo.name const url = response.url const res = await bindFileAndUserAPI({ name, url }) if (res.status == 0) { ElMessage.success('上傳成功') getCurrentPageData() getFilesLength() } else ElMessage.error('上傳失敗') } else { ElMessage.error('上傳失敗,請檢查是否重名') } } // 超出文件個數限制的鉤子 const handleExceed = (uploadFile, uploadFiles) => { } // 下載文件 const downloadFile = async (row) => { // console.log(row) const { download_number, id } = row await updateDownloadTimesAPI({ download_number, id }) const url = row.file_url const link = document.createElement('a') link.href = url link.setAttribute('download', '') document.body.appendChild(link) link.click() document.body.removeChild(link) getCurrentPageData() } // 刪除文件 const deleteFile = async row => { const res = await deleteFileAPI({ id: row.id }) if (res.status == 0) ElMessage.success('刪除成功') else ElMessage.error('刪除失敗') getCurrentPageData() getFilesLength() } // 分頁 const paginationData = ref({ // 總頁數 pageCount: 1, // 當前頁 currentPage: 1, }) // 獲取數據總數 const filesLength = ref(0) const getFilesLength = async () => { const res = await getFilesLengthAPI() filesLength.value = res.filesCount } // 獲取首頁數據 const getFirstPageList = async () => { const res = await returnFileListDataAPI({ page: 1 - 1 }) res.forEach(item => { item.upload_time = item.upload_time?.slice(0, 19) item.file_size = Math.floor(item.file_size) + 'kb' }) tableData.value = res } // 頁碼切換 const currentPageChange = async (val) => { paginationData.value.currentPage = val const res = await returnFileListDataAPI({ page: val - 1 }) res.forEach(item => { item.upload_time = item.upload_time?.slice(0, 19) item.file_size = Math.floor(item.file_size) + 'kb' }) tableData.value = res } // 增刪數據后,需要刷新當前頁數據 const getCurrentPageData = async () => { const res = await returnFileListDataAPI({ page: paginationData.value.currentPage - 1 }) res.forEach(item => { item.upload_time = item.upload_time?.slice(0, 19) item.file_size = Math.floor(item.file_size) + 'kb' }) tableData.value = res } onMounted(() => { getFilesLength() getFirstPageList() }) </script> <style lang="scss" scoped> .pane-content { margin-top: 8px; display: flex; flex-direction: column; justify-content: space-between; height: calc(100vh - 118px); background: #fff; .pane-top { padding: 8px; background: #fff; .module-common-header { padding: 0 20px; display: flex; align-items: center; justify-content: flex-end; } .module-common-table { min-height: 10px; padding: 10px 20px 20px; margin-bottom: 8px; background: #fff; } } .table-footer { display: flex; justify-content: flex-end; margin-bottom: 8px; } } </style>
我用的是vue3+setup語法糖寫法,代碼比較長,關注一下與下載相關的代碼:
html部分
<el-table-column fixed="right" label="操作"> <template #default="scope"> <el-button type="primary" size="small" @click="downloadFile(scope.row)">下載文件</el-button> <el-popconfirm title="確定刪除該文件嗎?" confirm-button-text="是" cancel-button-text="否" @confirm="deleteFile(scope.row)"> <template #reference> <el-button type="danger" size="small">刪除文件</el-button> </template> </el-popconfirm> </template> </el-table-column>
其實就是表格最后一列,添加兩個按鈕,然后為這個按鈕傳入本行的所有數據,下載文件按鈕添加點擊函數downloadFile,并傳入行數據作為參數
JavaScript部分
js部分是實現點擊下載的核心,看downloadFile方法
// 下載文件 const downloadFile = async (row) => { // console.log(row) const { download_number, id } = row // 從行中獲取下載文件接口的傳入參數 await updateDownloadTimesAPI({ download_number, id }) // 調用下載文件的接口 const url = row.file_url // 從行數據中獲取下載鏈接 const link = document.createElement('a') // 創(chuàng)建鏈接標簽,即a標簽,并將dom命名為link link.href = url // 為dom為link的元素添加鏈接 link.setAttribute('download', '') // 為link設置下載屬性 document.body.appendChild(link) // 把創(chuàng)建并配置好的link dom添加到頁面文檔中 link.click() // 模擬dom的點擊事件 document.body.removeChild(link) // 從文檔中移出link節(jié)點 getCurrentPageData() // 調用寫好的方法刷新數據 }
相關的解釋我都寫在了上面的代碼中,其中下面兩個步驟不是必須的:
- await updateDownloadTimesAPI({ download_number, id }) ,點擊下載后,要在數據庫中標記,增加點擊量
- getCurrentPageData(),因為操作了數據庫,數據要更新,所以這是為了更新數據
以上就是vue3實現點擊按鈕下載文件功能的詳細內容,更多關于vue3下載文件功能的資料請關注腳本之家其它相關文章!
相關文章
vue 基于abstract 路由模式 實現頁面內嵌的示例代碼
這篇文章主要介紹了vue 基于abstract 路由模式 實現頁面內嵌的示例代碼,幫助大家更好的理解和使用vue框架,感興趣的朋友可以了解下2020-12-12