F2图表在Vue3中的使用方法

如何在 Vue 中使用 | F2 移动端可视化引擎,这个是官网上面说的配置方法。

F2/packages/f2-vue/examples/vue3/src/App.vue at master · antvis/F2 · GitHub这个是官方提供的vue3的例子。

我没有使用render的方式去创建图表,直接将F2组件写在了template中,所以jsx也就不需要配置了。在这里梳理一下使用步骤:

  1. 安装依赖
bash 复制代码
npm install @antv/f2 --save
npm install @antv/f-vue --save
  1. 页面代码
javascript 复制代码
<template>
  <div className="container">
    <!-- 总资产折线图 -->
    <Canvas
      :pixel-ratio="2"
      :style="{ width: '100%', height: '300px' }"
      :key="can1key"
    >
      <Chart :data="allTotalData" :scale="scaleConfig">
        <Axis field="date" />
        <Axis field="allTotal" />
        <Line x="date" y="allTotal" />
      </Chart>
    </Canvas>

    <!-- 收益折线图 -->
    <Canvas
      :pixel-ratio="2"
      :style="{ width: '100%', height: '300px', marginTop: '20px' }"
      :key="can2key"
    >
      <Chart :data="earningsData" :scale="scaleConfig">
        <Axis field="date" />
        <Axis field="allEarning" />
        <Line x="date" y="allEarning" />
      </Chart>
    </Canvas>
  </div>
</template>

<script lang="ts" setup>
import Canvas from '@antv/f-vue';
import { Chart, Axis, Line } from '@antv/f2';
import { ref } from 'vue';
import { getStatisticList } from './api';
import { getPositionList } from '../money/api';
import { Statistic } from '../money/type';

const allTotalData = ref<{ date: string; allTotal: number }[]>([]);
const earningsData = ref<{ date: string; allEarning: number }[]>([]);
const positionList = ref([]);
const can1key = ref('can1' + 0); // canvas的key,动态变化用于图表数据刷新
const can2key = ref('can2' + 0);

// 可选:配置坐标轴刻度(避免日期重叠)
const scaleConfig = {
  date: {
    range: [0, 1],
    tickCount: 5,
  },
};

async function init() {
  const data: Statistic[] = await getStatisticList({ type: 1 });
  allTotalData.value = data.map((i) => ({
    date: i.createTime.substring(5, 10),
    allTotal: i.allTotal,
  }));
  earningsData.value = data.map((i) => ({
    date: i.createTime.substring(5, 10),
    allEarning: i.allEarnings,
  }));
  can1key.value += 1; // 在远程数据返回后,修改canvas的key
  can2key.value += 1;

  positionList.value = await getPositionList({ type: 1 });
}
init();
</script>

<style scoped></style>

这是一个很简单的页面,页面中有两个基础折线图。

到此这个页面的使用方法就讲完了,看着还挺简单的。不过,这里面有个大坑,就是正常我们请求数据然后修改响应式数据,都能让表格刷新,但是这里不行,这个问题废了我很长时间,最后找到一个方法,就是给canvas组件加key,然后数据返回后,更新key,这样可以强制组件销毁并重建。

不过就在我查阅资料时,这个问题我有了自己的解决办法了,这个问题本质上是canvas不能对data的变化进行响应(源码暂未研究),那么我在初始化的时候先不创建图表,等数据返回后再创建,用v-if="data.length"就可以达到同样的效果,且少一次创建图表的过程,性能更高一点。

遇到问题记录一下,养成总结记录的好习惯。

相关推荐
前端付豪1 天前
Memory V1:让 AI 记住你的关键信息
前端·后端·llm
毛骗导演1 天前
@tencent-weixin/openclaw-weixin 插件深度解析(三):CDN 媒体服务深度解析
前端·架构
谁在黄金彼岸1 天前
Threejs实现 3D 看房效果
前端
谁在黄金彼岸1 天前
Threejs实现物理运动模拟
前端
bluceli1 天前
JavaScript动态导入与代码分割:优化应用加载性能的终极方案
javascript
kyriewen1 天前
原型与原型链:JavaScript 的“家族关系”大揭秘
前端·javascript·ecmascript 6
谁在黄金彼岸1 天前
Flutter应用在Windows 8上正常运行
前端
谁在黄金彼岸1 天前
Vue项目中引入three.js并加载GLB模型流程与常见问题
前端
谁在黄金彼岸1 天前
开发Chrome_Edge插件基本流程
前端
滴滴答答哒1 天前
layui表格头部按钮 加入下拉选项
前端·javascript·layui