前言
参考源码来源于B站up主峰华前端工程师,原作者源码地址。
提示:源码有很多实验特性<script setup>
的写法,不知道为什么我这里就报错,我改为普通setup()
写法了。
效果
代码
首先App.vue挂载一个存放柱状图的组件BarChart :
<template>
<div class="wrapper">
<BarChart class="chart" />
</div>
</template>
<script>
import BarChart from "./components/echarts/BarChart.vue";
export default {
components: {
BarChart
}
}
</script>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background: hsl(210deg, 20%, 10%);
}
/* 外层需要加一层样式设置宽高,要不出不来图 */
.wrapper {
width: 100vw;
height: 100vh;
display: grid;
place-items: center;
}
.wrapper .chart {
width: 50%;
height: 70%;
}
</style>
然后柱状图组件BarChart 里引入专门用来实例化echarts的组件和对应配置js:
<template>
<Chart :options="barChartOptionsFn()" />
</template>
<script>
import Chart from "./Chart.vue";
import barChartOptions from "../../chartsOptions/barChartOptions.js";
export default {
// 不知到为什么不能像源码一样直接在模板中调用,只能这样多此一举的写法
methods: {
barChartOptionsFn() {
return barChartOptions()
}
},
components: {
Chart
}
}
</script>
柱状图对应配置barChartOptions.js:
// 柱状图配置
export default function barChartOptions() {
return {
legend: {},
tooltip: {},
dataset: {
source: [
["product", "2012", "2013", "2014", "2015"],
["Matcha Latte", 41.1, 30.4, 65.1, 53.3],
["Milk Tea", 86.5, 92.1, 85.7, 83.1],
["Cheese Cocoa", 24.1, 67.2, 79.5, 86.4],
],
},
xAxis: [
{ type: "category", gridIndex: 0 },
{ type: "category", gridIndex: 1 },
],
yAxis: [{ gridIndex: 0 }, { gridIndex: 1 }],
grid: [{ bottom: "55%" }, { top: "55%" }],
series: [
// These series are in the first grid.
{ type: "bar", seriesLayoutBy: "row" },
{ type: "bar", seriesLayoutBy: "row" },
{ type: "bar", seriesLayoutBy: "row" },
// These series are in the second grid.
{ type: "bar", xAxisIndex: 1, yAxisIndex: 1 },
{ type: "bar", xAxisIndex: 1, yAxisIndex: 1 },
{ type: "bar", xAxisIndex: 1, yAxisIndex: 1 },
{ type: "bar", xAxisIndex: 1, yAxisIndex: 1 },
],
};
}
最后是实例化的组件Chart.vue:
<template>
<div class="container" ref="container"></div>
</template>
<!--让整个script都为setup-->
<script setup>
import { ref, onMounted, watch, toRefs, defineProps } from "vue";
import * as echarts from "echarts"; // 之后这里可以按需导入,不需要全部导入
// 定义一个props值---options用来接收echart的配置
const props = defineProps({
options: {
type: Object,
default: {},
required: true,
},
});
const { options } = toRefs(props);
const container = ref(null); // echarts实例挂载的dom,这样也能获取到dom对象?
const chart = ref(null); // 放echarts实例
// 等容器dom挂载完才能去实例化echarts
onMounted(() => {
chart.value = echarts.init(container.value, "dark");
chart.value.setOption(props.options);
});
// 监听echarts配置,有变化就更新实例
watch(
options,
(newOptions) => {
chart.value.setOption(newOptions);
},
{ deep: true }
);
</script>
<style scoped>
/* echarts挂载的dom必须写上大小 */
.container {
width: 100%;
height: 100%;
}
</style>
尾巴
其实整体的思路和vue2是差不多的,只是刚学vue3的setup()
写法,又被<script setup>
这种实验特性的写法搞蒙了。笑死,根本更新不停。