大家好我是前端新手小猿同学:
这篇文章主要给大家简单介绍一下封装一个Echarts星座展示全局组件的过程希望对大家的学习进步有所帮助,当然文章中可能存在理解不正确的地方希望大家可在评论区相互讨教,共同进步。。
npm install echarts --save
再main.js中引入
import echarts from 'echarts'
Vue.prototype.$echarts = echarts
//引入公共的组件文件
import components from './components/index'
Vue.use(components);
在于pages文件夹同级的目录下面创建components文件夹,创建index.js文件
import bar from './bar'// 组件
//全局注册组件
function plugin(Vue){
Vue.component('chartBar', bar);
}
export default plugin
<template>
<div ref="dom" class="charts chart-bar"></div>
</template>
<script>
import echarts from "echarts";
import {
on, off } from "@/libs/tools";
export default {
name: "ChartBar",
props: {
value: Object,
text: String,
name: String,
conversion: {
default: false,
},
},
data() {
return {
dom: null,
};
},
methods: {
resize() {
this.dom.resize();
},
initChart() {
this.$nextTick(() => {
let option = {
title: {
text: this.text,
left: "left",
textStyle: {
fontSize: 16,
fontStyle: "normal",
color: "#333",
},
},
tooltip: {
backgroundColor: "rgba(0,0,0,0.8)",
padding: [10, 15, 10, 15],
trigger: "item",
formatter: "{a}
{b} : {c}",
},
grid: {
top: "30px",
left: "20px",
right: "20px",
bottom: "0px",
containLabel: true,
},
xAxis: [
{
type: "category",
data: this.value.xAxis.data,
axisTick: {
alignWithLabel: true,
},
axisLabel: {
color: "#333",
},
axisLine: {
show: true,
lineStyle: {
color: "#DDDDDD",
width: 1,
},
},
},
],
yAxis: [
{
type: "value",
axisTick: {
show:false,
alignWithLabel: false,
},
splitLine: {
show: true,
lineStyle: {
type: "dashed",
},
},
axisLabel: {
color: "#333",
},
axisLine: {
show: true,
lineStyle: {
color: "#DDDDDD",
width: 1,
},
},
},
],
series: [
{
name: this.name,
type: "bar",
barWidth: "24px",
itemStyle: {
color: "#4586FF",
},
label: {
show: true,
position: "top",
color: "#333",
},
data: this.value.series.data,
},
],
};
this.dom.setOption(option);
// 防止初始化时图表大小错误
this.resize();
});
},
},
mounted() {
this.dom = echarts.init(this.$refs.dom, "tdTheme");
on(window, "resize", this.resize);
},
beforeDestroy() {
off(window, "resize", this.resize);
},
watch: {
value: {
handler(val, oldVal) {
this.initChart();
},
deep: true,
immediate: true,
},
},
};
</script>
在index.vue中调用,使用props传值的方式,将父组件获取的后台数据传递给子组件
<chart-bar
:showLegend="true"
style="width: 900px; height: 700px"
:value="MapData"
text="柱状图"
name="星座图"
/>
这篇文章主要是给大家介绍了如何在Vue项目中使用echarts图表,当然更多的是介绍如何封装一个全局的组件,组件化开发是Vue的特点,所以希望大家在开发的过程中能够更多的使用组件。