vue使用mammoth.js实现浏览器渲染html

2,867 阅读1分钟

安装依赖:

npm install --save mammoth

有两种使用方式:

<template>
  <div>
    <input type="file" name="file" @change="changeFile" />
    <div id="wordView" v-html="wordText" />
  </div>
</template>

<script>
import mammoth from "mammoth";

export default {
  data() {
    return {
      wordText: "",
      wordURL: "",
    };
  },
  created() {
    // this.getWordText();    //调用线上接口
  },
  methods: {
    //选择本地文件预览
    changeFile(event) {
      let that = this;
      let file = event.target.files[0];
      let reader = new FileReader();
      reader.onload = function (loadEvent) {
        let arrayBuffer = loadEvent.target.result; //arrayBuffer
        mammoth
          .convertToHtml({ arrayBuffer: arrayBuffer })
          .then(that.displayResult)
          .done();
      };
      reader.readAsArrayBuffer(file);
    },
    //页面渲染
    displayResult(result) {
      this.wordText = result.value;
    },
    //调用后台文档下载接口
    getWordText() {
      console.log(this.wordURL);
      let that = this;
      const xhr = new XMLHttpRequest();
      xhr.open("get", "http://127.0.0.1:3000/downFile", true);
      xhr.responseType = "arraybuffer";
      xhr.onload = function () {
        if (xhr.status == 200) {
          mammoth
            .convertToHtml({ arrayBuffer: new Uint8Array(xhr.response) })
            .then(that.displayResult);
        }
      };
      xhr.send();
    },
  },
};
</script>

参考链接:
blog.csdn.net/qq_38143787…