<template>
<div id="cost">
<div class="costWrap">
<div class="costEcharts">
<div id="costec" class="echarts" style="width: 350px;height: 242px;"></div>
</div>
</div>
</div>
</template>
<script>
// 引入 echarts 核心模块,核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core'
// 引入柱状图图表,图表后缀都为 Chart
import {
BarChart, PieChart
} from 'echarts/charts'
// 引入提示框,标题,直角坐标系组件,组件后缀都为 Component
import {
TitleComponent,
TooltipComponent,
GridComponent
} from 'echarts/components'
// 引入 Canvas 渲染器,注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import {
CanvasRenderer
} from 'echarts/renderers'
// 注册必须的组件
echarts.use(
[TitleComponent, PieChart, TooltipComponent, GridComponent, BarChart, CanvasRenderer]
)
export default {
name: 'Cost',
components: {
},
data () {
return {
myChart: {},
option: {
tooltip: {
trigger: 'item',
// formatter: '{b} : {c} ({d}%)',
formatter: function (param) {
return param.marker + ' ' +
' ' + param.name + ':' + param.value + ' : ' + param.percent + '%'
},
backgroundColor: 'rgba(50, 50, 50, 0.7)',
borderColor: 'rgb(51, 51, 51)',
padding: [3, 8],
textStyle: {
color: '#fff',
align: 'left',
fontSize: 12
}
},
series: [
{
name: '访问来源',
type: 'pie',
radius: ['50%', '70%'], // 饼图的半径。 可以将内半径设大显示
avoidLabelOverlap: false,
startAngle: 180,
label: {
formatter: '{b}',
position: 'outside',
color: '#FFF'
},
itemStyle: {
borderWidth: 1,
borderColor: '#fff'
},
data: [
{ value: 1048, name: '搜索引擎' },
{ value: 735, name: '直接访问' },
{ value: 580, name: '邮件营销' },
{ value: 484, name: '联盟广告' },
{ value: 300, name: '视频广告' }
]
}
]
}
}
},
created () {
this.$nextTick(() => {
this.fetch()
})
},
methods: {
init () {
const _this = this
window.addEventListener('resize', () => {
console.log('init')
_this.myChart.resize()
})
},
fetch () {
this.myChart = echarts.init(document.getElementById('costec'))
this.myChart.setOption(this.option)
window.addEventListener('resize', this.myChart.resize)
}
},
mounted () { // 钩子
this.fetch()
window.addEventListener('resize', () => { this.myChart.resize() })
console.log(document.getElementById('costec').offsetWidth)
console.log(document.getElementById('costec').offsetHeight)
}
}
</script>
刷新的时候就如下面的图
打印出来的 宽度和高度 32 * 22
拉窗口就正常了
把这段代码从created
放到mounted
里面试试
this.$nextTick(() => {
this.fetch()
})