目錄
- 一、創建項目
- 二、項目引入echarts
- 1、下載依賴
- 2、項目引用
- 3、編寫建議echarts圖表
- 三、打印功能
- 1、增加打印按鈕
- 2、打印方法
- 3、效果
一、創建項目
老規矩,先從創建項目開始
npm create vite@latest print-demo(項目名稱)
第一步出現的框架選擇vue,然后回車
第二步的語言就選TS,一般vue3都是搭配TS使用的,選擇后回車
然后會出現三個指令,三個指令都是依次執行的,缺一不可,
依次執行完成以后,會出現一個地址,這個地址就是項目的地址,按住ctrl然后鼠標點擊,就可以直接打開項目了
然后打開就是這樣的一個頁面,
二、項目引入echarts
1、下載依賴
官網中有詳細介紹,感興趣的可以看看官網地址
2、項目引用
官網中有詳細介紹,我這里就跳過這一步,直接先寫一個實例出來
3、編寫建議echarts圖表
官網上例子很多,我就不做詳細介紹了,直接貼我用的官網的一個例子
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import * as echarts from 'echarts';
defineProps<{ msg: string }>()const count = ref(0)
const option = ref({tooltip: {trigger: 'axis',axisPointer: {type: 'cross',label: {backgroundColor: '#6a7985'}}},legend: {data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']},grid: {left: '3%',right: '4%',bottom: '3%',containLabel: true},xAxis: [{type: 'category',boundaryGap: false,data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']}],yAxis: [{type: 'value'}],series: [{name: 'Email',type: 'line',stack: 'Total',areaStyle: {},emphasis: {focus: 'series'},data: [120, 132, 101, 134, 90, 230, 210]},{name: 'Union Ads',type: 'line',stack: 'Total',areaStyle: {},emphasis: {focus: 'series'},data: [220, 182, 191, 234, 290, 330, 310]},{name: 'Video Ads',type: 'line',stack: 'Total',areaStyle: {},emphasis: {focus: 'series'},data: [150, 232, 201, 154, 190, 330, 410]},{name: 'Direct',type: 'line',stack: 'Total',areaStyle: {},emphasis: {focus: 'series'},data: [320, 332, 301, 334, 390, 330, 320]},{name: 'Search Engine',type: 'line',stack: 'Total',label: {show: true,position: 'top'},areaStyle: {},emphasis: {focus: 'series'},data: [820, 932, 901, 934, 1290, 1330, 1320]}]
})
const operateCharts = ref<HTMLElement | null>(null)
onMounted(() => {initChart()
})
const initChart = () => {if (operateCharts.value) {const chart = echarts.init(operateCharts.value)chart.setOption(option.value)window.addEventListener('resize', function () {chart.resize()})}}
</script><template><div ref="operateCharts" style="width: 500px;height:500px"></div>
</template><style scoped>
.read-the-docs {color: #888;
}
</style>
這個代碼出來的效果如下
三、打印功能
1、增加打印按鈕
代碼增加如下
<template><div ref="operateCharts" style="width: 500px;height:500px"></div><button>打印</button>
</template>
頁面如下,我這里給按鈕加了一個邊框,讓按鈕看的更清楚,大家可加可不加
在style.css中
2、打印方法
①給按鈕綁定方法
<button @click="Print">打印</button>//寫一個空的方法const Print = ()=>{}
②直接調用window.print();
const Print = () => {window.print();
}
3、效果
點擊打印,就調出打印的頁面了,這是最簡單的一個方式,后期會更新稍微復雜一些的,請關注后期帖子