vue 如何打開接口返回的HTML文件
前言:接口測試平臺,后端使用django,前端使用vue+element。項目接口平臺測試完成,需要把后臺產(chǎn)生的測試報告返回給前端展示。
一、后端接口
1、配置下django的template的參數(shù),templates文件夾是放在project的目錄下面的,是項目中或者說項目中所有的應用公用的一些模板
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'userfiles')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
2、視圖函數(shù),讀取template目錄下report文件夾的報告,并返回給前端
def getReport(self, request): # 獲取POST BODY信息 reportId = request.data["id"] try: print(os.getcwd()) # 打印程序運行目錄 template = loader.get_template(f"./report/{reportId}.html") # template = loader.get_template(f"1.html") return Response(template.render()) # return HttpResponse(template.render()) except Exception as e: content = {'message': '獲取報告失敗'} return Response(content)
二、前端
1、如果后端返回的HTML文件不包含js文件,可以使用vue的v-html,vue的v-html只能渲染html元素和css文件,,不能執(zhí)行js文件
2、后端返回的數(shù)據(jù),HTML文件包含js文件。使用下面這種方法,接口獲取到的html數(shù)據(jù)在暫存的本地localStorage,再讀取數(shù)據(jù),然后在新窗口打開報告。
接口返回的數(shù)據(jù)如下:
template:
<el-button type="warning" @click="viewReport" :disabled="reportDisabled
methods:
// 查看測試報告 viewReport () { var message = {id:1} // axios 通過接口獲取后臺的報html告文件數(shù)據(jù) getReport(message).then(res => { this.$message({ showClose: true, message: res.data.message, type: 'success' }) // res.data 為接口返回的html完整文件代碼 // 必須要存進localstorage,否則會報錯,顯示不完全 window.localStorage.removeItem('callbackHTML') window.localStorage.setItem('callbackHTML', res.data) // 讀取本地保存的html數(shù)據(jù),使用新窗口打開 var newWin = window.open('', '_blank') newWin.document.write(localStorage.getItem('callbackHTML')) // 關(guān)閉輸出流 newWin.document.close() }).catch(err => { this.$message({ showClose: true, message: err.response.msg, type: 'error' }) }) }
至此結(jié)束,點擊下按鈕即可在新窗口展示測試報告了
到此這篇關(guān)于vue 如何打開接口返回的HTML文件的文章就介紹到這了,更多相關(guān)vue 打開接口返回的HTML文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue3.x中useRouter()執(zhí)行后返回值是undefined問題解決
這篇文章主要給大家介紹了關(guān)于vue3.x中useRouter()執(zhí)行后返回值是undefined問題的解決方法,文中通過代碼示例介紹的非常詳細,對大家學習或者使用vue3.x具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09element-ui中導航組件menu的一個屬性:default-active說明
這篇文章主要介紹了element-ui中導航組件menu的一個屬性:default-active說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05Vue 使用Props屬性實現(xiàn)父子組件的動態(tài)傳值詳解
今天小編就為大家分享一篇Vue 使用Props屬性實現(xiàn)父子組件的動態(tài)傳值詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11一篇看懂vuejs的狀態(tài)管理神器 vuex狀態(tài)管理模式
一篇看懂vuejs的狀態(tài)管理神器,Vuex一個專為Vue.js應用程序開發(fā)的狀態(tài)管理模式,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04