用vue3+ts+echarts写一个双y轴折线图,不使用组件
时间: 2024-01-15 20:03:38 浏览: 90
好的,下面是实现代码:
```html
<template>
<div class="chart-container">
<canvas ref="chartCanvas"></canvas>
</div>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref } from "vue";
import * as echarts from "echarts";
export default defineComponent({
name: "DualAxisLineChart",
setup() {
const chartCanvas = ref<HTMLCanvasElement | null>(null);
onMounted(() => {
if (chartCanvas.value) {
const chart = echarts.init(chartCanvas.value);
chart.setOption({
tooltip: {
trigger: "axis",
axisPointer: {
type: "cross",
animation: false,
label: {
backgroundColor: "#505765",
},
},
},
xAxis: [
{
type: "category",
data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
axisPointer: {
type: "shadow",
},
},
],
yAxis: [
{
type: "value",
name: "y1",
min: 0,
max: 100,
interval: 20,
axisLabel: {
formatter: "{value} %",
},
},
{
type: "value",
name: "y2",
min: 0,
max: 500,
interval: 100,
axisLabel: {
formatter: "{value} km",
},
},
],
series: [
{
name: "data1",
type: "line",
yAxisIndex: 0,
data: [30, 40, 50, 60, 70, 80, 90],
},
{
name: "data2",
type: "line",
yAxisIndex: 1,
data: [100, 200, 300, 400, 450, 480, 500],
},
],
});
}
});
return {
chartCanvas,
};
},
});
</script>
<style scoped>
.chart-container {
width: 100%;
height: 400px;
}
</style>
```
这里使用了 `echarts` 库来实现双 y 轴折线图,具体的实现过程如下:
1. 在 `template` 中添加一个 `canvas` 元素,用于渲染图表;
2. 在 `setup` 中使用 `onMounted` 钩子,在组件挂载时初始化 `echarts` 实例,并设置图表的配置项;
3. 在 `return` 中返回 `chartCanvas`,该值被绑定到 `canvas` 的 `ref` 上,用于在初始化时获取 `canvas` 元素。
以上就是使用 `vue3` + `ts` + `echarts` 实现双 y 轴折线图的代码。
阅读全文