怎么做網(wǎng)站的內(nèi)鏈高質(zhì)量內(nèi)容的重要性
需求導(dǎo)入的下載模版不想放在服務(wù)器放在前端本地下載靜態(tài)資源最簡單的方式直接訪問 public 文件夾下的文件
方法一:使用靜態(tài)文件路徑
將文件放在 public 文件夾中:
把你的文件從 src/assets 移動到 public 文件夾。例如:public/template.xls。
在 Vue 組件中使用相對路徑:
<template><div><button @click="downloadTemplate">下載模板</button></div>
</template><script>
export default {methods: {downloadTemplate() {// 使用相對路徑const fileUrl = '/template.xls';// 創(chuàng)建一個隱藏的a標(biāo)簽const link = document.createElement('a');link.href = fileUrl;link.download = 'template.xls'; // 設(shè)置下載文件名// 將a標(biāo)簽添加到DOM并觸發(fā)點(diǎn)擊事件document.body.appendChild(link);link.click();// 移除a標(biāo)簽document.body.removeChild(link);}}
}
</script><style scoped>
/* 你的樣式代碼 */
</style>
二、確保項(xiàng)目目錄如下
my-vue-project/
├── public/
│ └── template.xls
├── src/
│ ├── assets/
│ ├── components/
│ └── App.vue
└── vue.config.js
三、驗(yàn)證
啟動你的開發(fā)服務(wù)器,通常是 npm run serve或npm run dev。
直接在瀏覽器中訪問 http://localhost:9000/template.xlsx 看是否能訪問到文件。
通過以上步驟,應(yīng)該能夠確保靜態(tài)文件能夠正確訪問和下載