使用windows.print进行页面打印的一种方式

<template>
  <div>
    <el-row class="do-exam-title">
      <el-col :span="24">
        <span :key="item.itemOrder" v-for="item in answer.answerItems">
             <el-tag :type="questionCompleted(item.completed)" class="do-exam-title-tag"
                     @click="goAnchor('#question-'+item.itemOrder)">{{ item.itemOrder }}</el-tag>
        </span>
      </el-col>
    </el-row>
    <el-row class="do-exam-title-hidden">
      <el-col :span="24">
        <span :key="item.itemOrder" v-for="item in answer.answerItems">
             <el-tag class="do-exam-title-tag">{{ item.itemOrder }}</el-tag>
        </span>
      </el-col>
    </el-row>
    <el-container class="app-item-contain">
      <div id="printcontent">
        <el-header class="align-center">
          <h1>{{ form.name }}</h1>
          <div>
            <span class="question-title-padding">试卷总分:{{ form.score }}</span>
            <span class="question-title-padding">考试时间:{{ form.suggestTime }}分钟</span>
          </div>
        </el-header>
        <el-main>
          <el-form :model="form" ref="form" v-loading="formLoading" label-width="100px">
            <el-row :key="index" v-for="(titleItem,index) in form.titleItems">
              <h3>{{ titleItem.name }}</h3>
              <el-card class="exampaper-item-box" v-if="titleItem.questionItems.length!==0">
                <el-form-item :key="questionItem.itemOrder"
                              v-for="(questionItem,index) in titleItem.questionItems"
                              class="exam-question-item" label-width="50px" :id="'question-'+ questionItem.itemOrder">
                  <QuestionEdit :qType="questionItem.questionType" :question="questionItem"
                                :answer="answer.answerItems[questionItem.itemOrderNew-1]" :index="index"/>
                </el-form-item>
              </el-card>
            </el-row>
          </el-form>
        </el-main>
      </div>
    </el-container>
    <el-row class="do-align-center">
      <el-button @click="doPrint3()">打印试卷</el-button>
    </el-row>
  </div>
</template>

<script>
import {mapState, mapGetters} from 'vuex'
import {formatSeconds} from '@/utils'
import QuestionEdit from '../question/components/QuestionEdit'
import examPaperApi from '@/api/examPaper'
import examPaperAnswerApi from '@/api/examPaperAnswer'

export default {
  components: {QuestionEdit},
  data() {
    return {
      form: {},
      formLoading: false,
      answer: {
        questionId: null,
        doTime: 0,
        answerItems: []
      },
      newOrder: 0,
      timer: null,
      remainTime: 0
    }
  },
  created() {
    let id = this.$route.query.id
    let _this = this
    if (id && parseInt(id) !== 0) {
      _this.formLoading = true
      examPaperApi.select(id).then(re => {
        console.log(re.response)
        if (re.response.titleItems) {
          re.response.titleItems.forEach(t => {
            if (t.questionItems.length > 0) {
              _this.shuffle(t.questionItems)
            }
          })
        }

        _this.form = re.response

        _this.remainTime = re.response.suggestTime * 60
        _this.initAnswer()
        _this.formLoading = false
      })
    }
  },
  mounted() {

  },
  beforeDestroy() {
    window.clearInterval(this.timer)
  },
  methods: {
    shuffle(arr) {
      let len = arr.length
      for (let i = 0; i < len - 1; i++) {
        let index = parseInt(Math.random() * (len - i))
        let temp = arr[index]
        arr[index] = arr[len - i - 1]
        arr[len - i - 1] = temp
      }
      arr.forEach(a => {
        this.newOrder++
        a.itemOrderNew = this.newOrder
      })

      console.log('乱序:', arr)
      return arr
    },
    formatSeconds(theTime) {
      return formatSeconds(theTime)
    },
    questionCompleted(completed) {
      return this.enumFormat(this.doCompletedTag, completed)
    },
    goAnchor(selector) {
      this.$el.querySelector(selector).scrollIntoView({
        behavior: 'instant',
        block: 'center',
        inline: 'nearest'
      })
    },
    initAnswer() {
      this.answer.id = this.form.id
      let titleItemArray = this.form.titleItems
      for (let tIndex in titleItemArray) {
        let questionArray = titleItemArray[tIndex].questionItems
        for (let qIndex in questionArray) {
          let question = questionArray[qIndex]
          this.answer.answerItems.push({
            questionId: question.id,
            title: question.title,
            content: null,
            contentArray: [],
            completed: false,
            itemOrder: question.itemOrder
          })
        }
      }
    },
    isIE: function () {
      if (!!window.ActiveXObject || "ActiveXObject" in window) {
        return true;
      } else {
        return false;
      }
    },
    doPrint3() {

      //判断iframe是否存在,不存在则创建iframe
      var iframe = document.getElementById("print-iframe");
      var el = document.getElementById("printcontent");
      iframe = document.createElement('IFRAME');
      var doc = null;
      iframe.setAttribute("id", "print-iframe");
      iframe.setAttribute("style", "position:absolute;width:0px;height:0px;left:-500px;top:-500px;");
      document.body.appendChild(iframe);
      doc = iframe.contentWindow.document;
      //这里可以自定义样式
      // doc.write(''); //解决出现页眉页脚和路径的问题

      // doc.write(''); //解决出现页眉页脚和路径的问题
      doc.write(''); //解决出现页眉页脚和路径的问题
      // doc.write(''); //解决出现页眉页脚和路径的问题
      doc.write('
' + el.innerHTML + '
'
); doc.close(); iframe.contentWindow.focus(); let that = this setTimeout(function () { // iframe.contentWindow.print(); if (that.isIE()) { document.body.className += ' ext-ie'; document.execCommand('print', true, null); } else { iframe.contentWindow.print(); } }, 50) //解决第一次样式不生效的问题 if (navigator.userAgent.indexOf("MSIE") > 0) { document.body.removeChild(iframe); } } }, computed: { ...mapGetters('enumItem', ['enumFormat']), ...mapState('enumItem', { doCompletedTag: state => state.exam.question.answer.doCompletedTag }) } } </script> <style lang="scss" scoped> .align-center { text-align: center } .exam-question-item { padding: 10px; .el-form-item__label { font-size: 15px !important; } } .question-title-padding { padding-left: 25px; padding-right: 25px; } </style>

效果如图:
使用windows.print进行页面打印的一种方式_第1张图片
不是很喜欢,已弃用

你可能感兴趣的:(工作总结,vue,javascript,前端,开发语言)