本教程操作環(huán)境:Windows10系統(tǒng)、Vue 3版、Dell G3電腦。
vue可以操作本地文件嗎?
可以。
(資料圖片僅供參考)
Vue項(xiàng)目通過讀取本地文件內(nèi)容來顯示內(nèi)容
公司項(xiàng)目需要在登陸之前,實(shí)現(xiàn)客戶自定義項(xiàng)目標(biāo)題。由于還未登陸,所以肯定無法通過后端管理系統(tǒng)配置。 第一個(gè)想到的辦法是通過讀取本地文件內(nèi)容,來顯示標(biāo)題內(nèi)容。 客戶需要求改標(biāo)題時(shí),直接修改本地文件內(nèi)容即可。
讀取本地文件的思路有兩種,第一種是利用XMLHttpRequest,第二種是利用input的type=file將文件先上傳,再讀取。
利用XMLHttpRequest對本地文件進(jìn)行讀取操作,值得注意的是,HTML文檔的格式要與流中的讀取格式設(shè)置一致, 代碼如下:
methods: { readFile(filePath) { // 創(chuàng)建一個(gè)新的xhr對象 let xhr = null if (window.XMLHttpRequest) { xhr = new XMLHttpRequest() } else { // eslint-disable-next-line xhr = new ActiveXObject("Microsoft.XMLHTTP") } const okStatus = document.location.protocol === "file" ? 0 : 200 xhr.open("GET", filePath, false) xhr.overrideMimeType("text/html;charset=utf-8") xhr.send(null) return xhr.status === okStatus ? xhr.responseText : null },}首先創(chuàng)建一個(gè)讀取文件內(nèi)容的函數(shù)readFile,通過XMLHttpRequest對象,讀取指定路徑中的文件,格式指定為text/html,并返回內(nèi)容。 然后直接在login組件的created鉤子函數(shù)中,調(diào)用并讀取文件內(nèi)容,賦值給需要顯示的標(biāo)題title屬性。
created() { this.getList() this.title = this.readFile("../../../static/title.txt") console.log(this.title) },本次項(xiàng)目需求就是使用此方案解決。
上傳文件利用input標(biāo)簽,然后使用FileReader對象,h5提供的異步api,可以讀取文件中的數(shù)據(jù)。
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <span>點(diǎn)擊上傳:</span> <input type="file" id="files1" onchange="uploadFile1()"> <br> <span>點(diǎn)擊上傳2:</span> <input type="file" id="files2" onchange="uploadFile2(event)"> <script> function uploadFile1() { const selectedFile = document.getElementById("files1").files[0] // 讀取文件名 const name = selectedFile.name // 讀取文件大小 const size = selectedFile.size // FileReader對象,h5提供的異步api,可以讀取文件中的數(shù)據(jù)。 const reader = new FileReader() // readAsText是個(gè)異步操作,只有等到onload時(shí)才能顯示數(shù)據(jù)。 reader.readAsText(selectedFile) reader.onload = function () { //當(dāng)讀取完成后回調(diào)這個(gè)函數(shù),然后此時(shí)文件的內(nèi)容存儲到了result中,直接操作即可 console.log(this.result); } } function uploadFile2(e) { const selectedFile = e.target.files[0] const reader = new FileReader() // 文件內(nèi)容載入完畢之后的回調(diào)。 reader.onload = function(e) { console.log(e.target.result) } reader.readAsText(selectedFile) } </script> </body></html>推薦學(xué)習(xí):《vue視頻教程》以上就是vue可以操作本地文件嗎的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
關(guān)鍵詞: