1.安装两个依赖:vega和vega-lite
2.使用很简单,请参考
https://juejin.cn/post/6844903945106620424
3.这里详细说一下如何调用Vega自带的下载矢量图和位图功能,本来是可以直接下载,但UI设计图一般是把下载按钮自定义了,如果你想的是通过js触发自带按钮的click事件,嗯,想法是对的,但是最终效果却令人头大,可以试一试,是出不来想要的效果的,这里我加了一个定时器事件,这样就可以触发自带按钮的click事件了。
<template>
<div class="vegaGraph" ref="vegaGraph">
<div class="operateBtn">
<el-button type="primary" @click="downLoad(1)">矢量图</el-button>
<el-button type="primary" @click="downLoad(2)">位图</el-button>
</div>
<div id="view"></div>
</div>
</template>
<script>
import * as vega from 'vega'
import * as vegalite from 'vega-lite'
import vegaEmbed from 'vega-embed'
import $ from 'jquery'
import html2canvas from 'html2canvas'
export default {
name: 'vegaGraph',
components: {
},
data () {
return {
showOtherBtn: false,
spec: {
$schema: 'https://vega.github.io/schema/vega-lite/v5.4.0.json',
width: 400,
height: 300,
data: { url: 'https://cdn.jsdelivr.net/npm/vega-datasets@v1.29.0/data/population.json' },
mark: { type: 'boxplot', extent: 'min-max' },
encoding: {
x: { field: 'age', type: 'ordinal' },
y: { field: 'people', type: 'quantitative' }
},
selection: { selector001: { type: 'interval', bind: 'scales', encodings: ['x', 'y'] } }
}
}
},
computed: {
},
created () {
},
mounted () {
this.chart()
},
methods: {
downLoad (val) {
const event = new Event('mousedown')
document.querySelector(`a:nth-child(${val})`).addEventListener('mousedown', myFunctions, false)
function myFunctions () {
let time1 = setInterval(() => {
if ($($('a')[val - 1]).attr('href') && $($('a')[val - 1]).attr('href') !== '#') {
$('a')[val - 1].click()
clearInterval(time1)
myFunctions2()
}
}, 300)
}
function myFunctions2 () {
document.querySelector(`a:nth-child(${val})`).removeEventListener('mousedown', myFunctions)
}
document.querySelector(`a:nth-child(${val})`).dispatchEvent(event)
},
chart () {
vegaEmbed('#view', this.spec, {
renderer: 'svg',
defaultStyle: false,
actions: {
export: { png: true, svg: true },
source: false,
editor: false,
compiled: false
},
i18n: {
SVG_ACTION: '矢量图',
PNG_ACTION: '位图'
}
}).then(result => {
}).catch(console.error)
}
}
}
</script>
<style lang="scss" scoped>
.vegaGraph{
height: 100%;
display: flex;
background-color: #F0F2F5;
display: flex;
flex-direction: column;
.flexCenter{
display: flex;
justify-content: center;
align-items: center;
}
.operateBtn{
margin: 20px;
}
/deep/ .vega-actions{
a{
margin-right: 20px;
}
}
}
</style>
效果如下: