createNewChart.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <template>
  2. <div>
  3. <el-card class="box-card">
  4. <div slot="header" class="clearfix">
  5. <span>上传json文件,生成新的图表</span>
  6. <el-upload
  7. style="float: right; padding: 3px 0"
  8. class="upload-demo"
  9. action=""
  10. :before-upload="beforeUpload"
  11. :http-request="customUpload"
  12. multiple
  13. :file-list="fileList"
  14. >
  15. <el-button size="small" type="text">点击上传</el-button>
  16. <div slot="tip" class="el-upload__tip">只能上传json文件</div>
  17. </el-upload>
  18. </div>
  19. <div id="creatNewChart"></div>
  20. </el-card>
  21. </div>
  22. </template>
  23. <script>
  24. import Plotly from "plotly.js-dist";
  25. export default {
  26. data() {
  27. return {
  28. fileList: [], // 保存上传的文件
  29. mergedData: [], // 合并后的图表数据
  30. mergedLayout: {}, // 合并后的布局数据
  31. };
  32. },
  33. methods: {
  34. // 文件类型检查
  35. beforeUpload(file) {
  36. const isJSON =
  37. file.type === "application/json" || file.name.endsWith(".json");
  38. if (!isJSON) {
  39. this.$message.error("只能上传 JSON 文件");
  40. }
  41. return isJSON;
  42. },
  43. // 自定义上传方法
  44. customUpload({ file }) {
  45. const reader = new FileReader();
  46. reader.onload = (e) => {
  47. try {
  48. const jsonData = JSON.parse(e.target.result);
  49. this.mergeChartData(jsonData);
  50. this.generateChart();
  51. } catch (error) {
  52. this.$message.error("上传的文件不是有效的 JSON 格式");
  53. }
  54. };
  55. reader.readAsText(file); // 读取文件内容
  56. },
  57. // 合并图表数据
  58. mergeChartData(jsonData) {
  59. // 合并 data 部分
  60. this.mergedData = this.mergedData.concat(jsonData.data);
  61. // 合并 layout 部分,假设 layout 相同,否则需要根据需求处理
  62. if (Object.keys(this.mergedLayout).length === 0) {
  63. this.mergedLayout = jsonData.layout;
  64. }
  65. },
  66. // 生成图表
  67. generateChart() {
  68. const config = {
  69. displaylogo: false,
  70. editable: false,
  71. scrollZoom: true,
  72. };
  73. Plotly.newPlot(
  74. "creatNewChart",
  75. this.mergedData,
  76. this.mergedLayout,
  77. config
  78. );
  79. },
  80. },
  81. };
  82. </script>
  83. <style scoped>
  84. .text {
  85. font-size: 14px;
  86. }
  87. .item {
  88. margin-bottom: 18px;
  89. }
  90. .clearfix:before,
  91. .clearfix:after {
  92. display: table;
  93. content: "";
  94. }
  95. .clearfix:after {
  96. clear: both;
  97. }
  98. .box-card {
  99. width: 100%;
  100. }
  101. </style>