Vue3 打印函数页面有问题,元素错位,用的html2canvas

img

img


希望有朋友帮我指点一下下,谢谢呀,实在想不出来是哪里出错了,冥思苦想了很久

参考自 chat-gpt:
在Vue3中使用html2canvas进行截图时,可能会出现元素错位的问题。这是由于Vue3中的模板编译器和Vue2有所不同,导致生成的HTML代码与预期不符。解决方法如下:

安装@vue/compiler-sfc和@vue/compiler-dom两个包:

npm install @vue/compiler-sfc @vue/compiler-dom --save-dev

在vue.config.js中添加以下配置:

const { compileTemplate } = require('@vue/compiler-sfc')
module.exports = {
  chainWebpack: config => {
    config.module
      .rule('vue')
      .use('vue-loader')
      .tap(options => {
        options.compilerOptions = {
          ...options.compilerOptions,
          isCustomElement: tag => tag.startsWith('g-')
        }
        return options
      })
  },
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.html$/,
          loader: 'html-loader'
        }
      ]
    }
  },
  devServer: {
    open: true
  },
  pluginOptions: {
    electronBuilder: {
      preload: 'src/preload.js',
      builderOptions: {
        appId: 'com.example.app',
        productName: 'My App',
        win: {
          icon: 'public/icon.png',
          target: [
            {
              target: 'nsis',
              arch: [
                'x64',
                'ia32'
              ]
            }
          ]
        }
      }
    }
  }
}

在需要截图的组件中,使用compileTemplate将模板编译成HTML,并将HTML传递给html2canvas进行截图:

import { ref } from 'vue'
import html2canvas from 'html2canvas'
import { compileTemplate } from '@vue/compiler-sfc'
export default {
  setup() {
    const screenshot = ref(null)
    const handleScreenshot = () => {
      const template = `
        <div>
          <h1>Hello World</h1>
          <p>This is a test component</p>
        </div>
      `
      const { code } = compileTemplate({ source: template })
      const html = code.replace('export function', 'function')
      html2canvas(document.body.appendChild(document.createElement('div')).innerHTML = html, {
        useCORS: true
      }).then(canvas => {
        screenshot.value = canvas.toDataURL()
      })
    }
    return {
      screenshot,
      handleScreenshot
    }
  }
}