与main.js同级,创建utils文件夹,文件夹中创建myCharts.js文件
//引入基本模板
var echarts = require('echarts/lib/echarts')
// 引入折线图等组件
require('echarts/lib/chart/line')
require('echarts/lib/chart/bar')
require('echarts/lib/chart/radar')
// 引入提示框和title组件,图例
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
require('echarts/lib/component/legend')
require('echarts/lib/component/legendScroll')//图例翻译滚动
const install = function (Vue) {
Object.defineProperties(Vue.prototype, {
$chart: {
get() {
return {
//画一条简单的线
line: function (id, xAxisData, seriesData) {
this.chart = echarts.init(document.getElementById(id));
this.chart.clear();
const optionData = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line',
smooth: true
}]
};
this.chart.setOption(optionData);
this.chart.resize();
},
bar: function (id, xAxisData, seriesData) {
this.chart = echarts.init(document.getElementById(id));
this.chart.clear();
const optionData = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'bar',
smooth: true
}]
};
this.chart.setOption(optionData);
this.chart.resize();
},
}
}
}
})
}
export default {
install
}
main.js引入和挂载
import myCharts from './utils/myCharts.js';
Vue.use(myCharts);
页面中使用
export default {
data() {
return {
activeName: '1',
chartVisible: true
};
},
mounted() {
this.$chart.bar('mStudyTime');
this.$chart.line('passRate');
// 图标自适应(监听多个图表)
window.addEventListener('resize', () => {
this.$chart.bar('mStudyTime');
this.$chart.line('passRate');
});
},
methods: {
handleClick() {
if (this.activeName == '1') {
this.$nextTick(() => {
this.$chart.bar('mStudyTime');
});
}
if (this.activeName == '2') {
this.$nextTick(() => {
this.$chart.line('passRate');
});
}
}
}
};