vue点击下载按钮将输入的url链接导出后缀为html的文件
<div>
<el-form ref="updateAgreementContentRef"
:model="updateAgreementContentForm"
:rules="updateAgreementContentRules"
label-width="100px"
>
<el-row>
<el-col>
<el-form-item prop="extUrl">
<el-input v-model="updateAgreementContentForm.extUrl" type="url" placeholder="请输入URL链接" />
</el-form-item>
</el-col>
</el-row>
<el-form-item>
<el-button @click="batchDownload">下载导出/el-button>
</el-form-item>
</el-form>
</div>
data() {
return {
updateAgreementContentForm: {
extUrl: ''
},
updateAgreementContentRules: {
extUrl: [
{ required: true, message: '请输入URL链接', trigger: 'blur' },
{ validator: this.validateHttpsUrl, trigger: 'blur' }
]
},
}
},
methods: {
// 校验只能输入http或者https格式的url链接地址
validateHttpsUrl(rule, value, callback) {
const httpsUrlPattern = /^(https?:\/\/[^\s$.?#].[^\s]*)$/i
if (!httpsUrlPattern.test(value)) {
callback(new Error('请输入URL链接'))
} else {
callback()
}
},
// 下载文件
batchDownload() {
let a = document.createElement('a')
let url = window.URL.createObjectURL(
new Blob([this.getHtmlContent()], {
type: ''
})
)
a.href = url
a.download = `download.html` // 下载文件名称
a.click()
window.URL.revokeObjectURL(url)
},
// 获取文件内容转为html
getHtmlContent() {
// style="border: none;" 去除iframe黑色边框
const template = `<iframe src="${this.updateAgreementContentForm.extUrl}" style="border: none;"></iframe>`
const html = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>协议与政策</title>
</head>
<body>
<div class="page">
${template}
</div>
</body>
</html>`
return html
}
}