注意:该文章基于vue-cli4.5,vue-cli3以上都可以啦。
首先是依赖的准备:
jquery与jquery-table2excel-1.1.2
npm install jquery --save
const webpack = require("webpack");
module.exports = {
configureWebpack: {
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"windows.jQuery": "jquery",
}),
],
},
};
至此,jquery引入vue项目完成。
这个库是将表格转换成excel进行输出,所以前提是得把图表数据转换成表格。
github下载地址:我用的是1.1.2
下载解压之后,将文件夹丢到scr目录下。
在main.js中引入即可:
import "./jquery-table2excel-1.1.2/src/jquery.table2excel.js";
可以会出现引入echarts,但用不了echarts相应的方法的情况:
如果是5.0以上的版本,大多搜到的都是将版本,实际上改一下引入写法就好了:
import * as echarts from 'echarts'
<template>
<div id="pieChart" style="width: 500px; height: 400px">div>
template>
<script>
import echarts from "echarts";
export default {
name: "",
data() {
return {
opinion: ["o1", "o2", "o3", "o4", "o5"],
opinionData: [
{
value: 235, name: "o1" },
{
value: 340, name: "o2" },
{
value: 124, name: "o3" },
{
value: 35, name: "o4" },
{
value: 548, name: "o5" },
],
};
},
methods: {
drawPie(id) {
this.charts = echarts.init(document.getElementById(id));
this.charts.setOption({
tooltip: {
trigger: "item",
formatter: "{a}
{b}:{c} ({d}%)",
},
legend: {
orient: "vertical",
x: "left",
data: this.opinion,
},
series: [
{
name: "访问来源",
type: "pie",
radius: ["50%", "70%"],
avoidLabelOverlap: false,
label: {
normal: {
show: false,
position: "center",
},
emphasis: {
show: true,
textStyle: {
fontSize: "30",
fontWeight: "blod",
},
},
},
labelLine: {
normal: {
show: false,
},
},
data: this.opinionData,
},
],
toolbox: {
feature: {
dataView: {
show: true,
title: "数据视图",
lang: ["数据视图", "关闭", "导出Excel"],
contentToOption: function () {
//这里的#tableExcel ID 指的是table的ID 而非echarts图表
$("#tableExcel").table2excel({
filename: "测试.xls",
// 文件名称
name: "Excel Document Name.xls",
exclude_img: true,
exclude_links: true,
exclude_inputs: true,
});
},
// 将数据视图展示为table
optionToContent: function (opt) {
var seriesData = opt.series[0].data;
var tdHeads =
'名称 ' +
'数值 ';
var table =
'' +
tdHeads +
" ";
seriesData.forEach((obj) => {
table +=
'' +
obj.name +
" " +
"" +
obj.value +
" " +
"";
});
table += "
";
return table;
},
},
},
},
});
},
},
mounted() {
this.drawPie("pieChart");
},
};
script>