vue导出自定义的html

vue导出.html文件

HTML页面由.css、htmlDom标签组成,将css设置成js通过export导出,htmlDom可以通过$el.innerHTML获得,也可通过document.getElementById('id')获得 。然后构造html页面,使用createObjectURL创建一个文件流下载。代码如下:

import {resumecss} from '@/styles/download.css.js'
import writer from 'file-writer'
 
methods:{
    download(name){  
        let html = this.getHtml();
        let s = writer(`${name}.html`, html, 'utf-8');
    },
    getHtml(){
         const template = this.$refs.resume.innerHTML      
         let html = `<!DOCTYPE html>
                 <html>
                 <head>
                 <meta charset="utf-8">
                 <meta name="viewport" content="width=device-width,initial-scale=1.0">
                 <title>html</title>
                <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
                <style> ${resumecss} </style>
                </head>
                <body>
                <div style="margin:0 auto;width:1200px">
                ${template}
                </div>
                </body>
                </html>`
                return html
      },
}

安装 'file-writer' 包,也可以写原生代码。如下:

1> 安装 'file-writer' 包: npm install -D file-writer
2> 原生代码:(也可以方到  methods里面)
function writer(fileName,content,option){
     var a = document.createElement('a');
     var url = window.URL.createObjectURL(new Blob([content],
        { type: (option.type || "text/plain") + ";charset=" + (option.encoding || 'utf-8') }));
     a.href = url;
     a.download = fileName || 'file';
     a.click();
     window.URL.revokeObjectURL(url);
 }

download.css.js

export const resumecss = `
  html,body{
    padding: 0;
    margin: 0;
  }
  ...
`

最后直接调用哪个  download   方法就可以了,传递的就是你想给这个html取的名字

posted @ 2023-07-28 13:35  黑白棋学弟  阅读(992)  评论(0编辑  收藏  举报