html导出docx文件

1、npm安装

$ npm install --save html-docx-js
$ npm install --save file-saver

2、引入

import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';

3、点击事件实现导出

<template>
  <div class="about">
    <button @click="this.exportClick">an</button>
  </div>
</template>

<script>
import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';
export default {
  methods: {
    exportClick() {
      var content = ` <h1>This is an about page</h1>
      <h2>This is an about page</h2>`
      var page = '' + content + ''
      var converted = htmlDocx.asBlob(page);
      // 用 FielSaver.js里的保存方法 进行输出
      saveAs(converted, 'test.docx');
    }
  }
}
</script>

4、没事干,整理了一下写法

<script>
// 引入相关插件
import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';

export default {
    data(){
        return{
            // 页面渲染相关
            content:'',
            page:''
        }
    },
  methods: {
    exportDocx() {
      this.content = ` <h1>This is an about page</h1>
      <h2>This is an about page</h2>`;
      this.page = `<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>${this.content}</body></html>`
      const converted = htmlDocx.asBlob(this.page);
      // 用 FielSaver.js里的保存方法 进行输出
      saveAs(converted, 'test.docx');
    }
  },
  render() {
    return (
      <div class="about">
        <button onClick={this.exportDocx}>文件导出</button>
      </div>
    )
  }
}
</script>

你可能感兴趣的:(vue,html-docx-js,file-saver)