用vue3+ts+echarts写一个双y轴折线图
时间: 2023-10-31 09:17:10 浏览: 36
好的,以下是一个基于 Vue3 和 TypeScript 的双 Y 轴折线图的示例代码:
```vue
<template>
<div class="chart-container">
<div ref="chart" class="chart"></div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
export default defineComponent({
name: 'DoubleLineChart',
props: {
data: {
type: Array,
required: true
},
xAxisName: {
type: String,
default: ''
},
yAxisNameLeft: {
type: String,
default: ''
},
yAxisNameRight: {
type: String,
default: ''
}
},
setup(props) {
const chartRef = ref(null)
let chart: any = null
const initChart = () => {
chart = echarts.init(chartRef.value)
chart.setOption({
tooltip: {
trigger: 'axis'
},
legend: {
data: [props.yAxisNameLeft, props.yAxisNameRight]
},
xAxis: {
type: 'category',
name: props.xAxisName,
data: props.data.map((item: any) => item.name),
axisLabel: {
interval: 0,
rotate: 45
}
},
yAxis: [
{
type: 'value',
name: props.yAxisNameLeft,
position: 'left'
},
{
type: 'value',
name: props.yAxisNameRight,
position: 'right'
}
],
series: [
{
name: props.yAxisNameLeft,
type: 'line',
data: props.data.map((item: any) => item.value1),
yAxisIndex: 0
},
{
name: props.yAxisNameRight,
type: 'line',
data: props.data.map((item: any) => item.value2),
yAxisIndex: 1
}
]
})
}
onMounted(() => {
initChart()
})
watch(
() => props.data,
() => {
if (chart) {
chart.setOption({
xAxis: {
data: props.data.map((item: any) => item.name)
},
series: [
{
data: props.data.map((item: any) => item.value1)
},
{
data: props.data.map((item: any) => item.value2)
}
]
})
}
},
{ deep: true }
)
return {
chartRef
}
}
})
</script>
<style>
.chart-container {
width: 100%;
height: 100%;
}
.chart {
width: 100%;
height: 100%;
}
</style>
```
在父组件中使用该组件:
```vue
<template>
<div>
<double-line-chart
:data="data"
xAxisName="日期"
yAxisNameLeft="产量"
yAxisNameRight="销量"
></double-line-chart>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import DoubleLineChart from '@/components/DoubleLineChart.vue'
export default defineComponent({
name: 'App',
components: {
DoubleLineChart
},
data() {
return {
data: [
{ name: '2022-01-01', value1: 100, value2: 200 },
{ name: '2022-01-02', value1: 80, value2: 180 },
{ name: '2022-01-03', value1: 120, value2: 220 },
{ name: '2022-01-04', value1: 90, value2: 200 },
{ name: '2022-01-05', value1: 110, value2: 230 },
{ name: '2022-01-06', value1: 130, value2: 250 }
]
}
}
})
</script>
```
可以根据实际情况修改数据和配置。