Vue 3 使用 Print.js 打印 `<div>` 内容 - `<script setup>` 实现
在 Vue 3 中,可以使用<script setup>标签以组合式 API 的方式编写代码。要在<div id="printWeb">内部的内容上使用printjs打印,可以按照以下步骤进行操作:\n\n1. 首先,确保已经引入了printjs的相关文件。可以通过在HTML文件中添加以下代码来引入print.js的CDN:\nhtml\n<script src="https://printjs-4de6.kxcdn.com/print.min.js"></script>\n<link rel="stylesheet" href="https://printjs-4de6.kxcdn.com/print.min.css" />\n\n\n2. 在Vue单文件组件中,使用<script setup>标签,并导入onMounted函数和ref函数:\nvue\n<script setup>\nimport { onMounted, ref } from 'vue';\n\nconst printContentRef = ref(null);\n\nonMounted(() => {\n printjs({\n printable: printContentRef.value.innerHTML,\n type: 'html',\n });\n});\n</script>\n\n\n3. 在模板中,使用ref函数将<div id="printWeb">元素与printContentRef关联,并在<div>中添加需要打印的内容:\nvue\n<template>\n <div>\n <div id="printWeb" style="display: none" ref="printContentRef">\n <!-- 添加需要打印的内容 -->\n </div>\n <!-- 其他页面内容 -->\n </div>\n</template>\n\n\n通过上述步骤,当组件挂载后,printjs将会使用printContentRef.value.innerHTML中的内容进行打印。请注意,printContentRef是通过ref函数创建的响应式引用,可以通过printContentRef.value来访问关联的元素。
原文地址: https://www.cveoy.top/t/topic/p97s 著作权归作者所有。请勿转载和采集!