diff --git a/src/components/G2/G2.js b/src/components/G2/G2.js index f06b6751..1e1f3f46 100644 --- a/src/components/G2/G2.js +++ b/src/components/G2/G2.js @@ -1,11 +1,25 @@ import G2 from '@antv/g2' +// 关闭 G2 的体验改进计划打点请求 +G2.track(false) + export default { + props: { + data: { + type: Array, + required: false, + default: () => [] + } + }, data () { return { // 库 在页面中不需要再引入 直接使用 this.G2 G2, // 图表实例 chart: null, + // 在组件 mounted 后立即初始化图表 + mountedInit: true, + // [图表设置项] 标题 + title: '标题', // [图表设置项] 高度 height: 300, // [图表设置项] 开启自动填充父元素高度 @@ -23,9 +37,18 @@ export default { ]) }, mounted () { - setTimeout(() => { - this.initHandler() - }, 0) + // 如果设置了在 mounted 后自动初始化 就在这里初始化 + if (this.mountedInit) { + setTimeout(() => { + this.initHandler() + }, 0) + } + }, + watch: { + // 数据改变 + data () { + this.changeData() + } }, methods: { // 创建图表 @@ -38,26 +61,35 @@ export default { }) }, // 设置图表的标题 - setChartTitle (title) { - if (title) { - this.chart.guide().text({ - top: true, - position: ['min', 'max'], - content: title, - style: { - fill: '#666', // 文本颜色 - fontSize: '16', // 文本大小 - fontWeight: 'bold' // 文本粗细 - }, - offsetX: 0, - offsetY: 0 - }) - } + setChartTitle () { + this.chart.guide().text({ + top: true, + position: ['min', 'max'], + content: this.title, + style: { + fill: '#666', // 文本颜色 + fontSize: '16', // 文本大小 + fontWeight: 'bold' // 文本粗细 + }, + offsetX: 0, + offsetY: 0 + }) }, + // 重绘大小 resize () { if (this.chart) { this.chart.changeSize(this.G2.DomUtil.getWidth(this.$refs.chart), this.G2.DomUtil.getHeight(this.$refs.chart)) } + }, + // 数据源改变 重新渲染新的数据 + changeData () { + if (this.chart) { + // 已经初始化过图表 更新数据 + this.chart.changeData(this.data) + } else { + // 没有图表 新创建一个实例 + this.initHandler() + } } } } diff --git a/src/components/G2/Line1.vue b/src/components/G2/Line1.vue index 1915ea89..f3ed0e0c 100644 --- a/src/components/G2/Line1.vue +++ b/src/components/G2/Line1.vue @@ -8,21 +8,18 @@ export default { mixins: [ G2Mixin ], + data () { + return { + // 在组件 mounted 后立即初始化图表 + mountedInit: false + } + }, methods: { + // 初始化图表 initHandler () { - const data = [ - { year: '1991', value: 3 }, - { year: '1992', value: 4 }, - { year: '1993', value: 3.5 }, - { year: '1994', value: 5 }, - { year: '1995', value: 4.9 }, - { year: '1996', value: 6 }, - { year: '1997', value: 7 }, - { year: '1998', value: 9 }, - { year: '1999', value: 13 } - ] this.creatChart() - this.chart.source(data) + this.setChartTitle() + this.chart.source(this.data) this.chart.scale('value', { min: 0 }) @@ -34,7 +31,6 @@ export default { type: 'line' } }) - this.setChartTitle('历史趋势') this.chart.line().position('year*value') this.chart.point().position('year*value').size(4).shape('circle').style({ stroke: '#fff', diff --git a/src/pages/demo/chart/index/index.vue b/src/pages/demo/chart/index/index.vue index 783f0ea9..5187a292 100644 --- a/src/pages/demo/chart/index/index.vue +++ b/src/pages/demo/chart/index/index.vue @@ -1,12 +1,8 @@