在使用 uni-app 開發釘釘小程序時,想使用 antv f2 圖表庫,其中遇到的問題和解決方式。
官方提供的使用方式
F2 的支付寶小程序版本:
https://github.com/antvis/my-f2
項目中安裝F2
npm install @antv/my-f2 --save
使用json文件,引入組件
{
"usingComponents": {
"f2": "@antv/my-f2"
}
}
運行結果 頁面報錯:
json文件引入組件 報錯
不是單單引入@antv/my-f2 會報錯。
而是在uni-app中通過 usingComponents 引入mycomponents下的組件都會報錯。
如,自定義一個測試組件:
測試自定義組件
{
"usingComponents": {
"my-test": "/mycomponents/my-test/my-test"
}
}
這個你們可以測試下,一樣會報錯。
反正在釘釘環境下,我使用 json文件的方式 來引入自定義組件,就沒有成功過。
如果頁面中直接 import 導入組件行不行呢?
...
<script>
import AntvF2 from '@antv/my-f2'
export default {
components: {
AntvF2
}
}
</script>
這個錯得更離譜,直接整個項目崩了。
import導入組件 報錯
最終解決方式
首先
把支付寶小程序my-f2 中相關的代碼提取出來,整合成uni-app中的自定義組件。
代碼地址:https://github.com/yiPian/f2-canvas-to-dd
然后
放置在uni-app項目里面的 mycomponents 文件夾中。
如圖:
組件存放目錄
最后使用組件
<template>
<view>
<f2-canvas :on-init="onInitChart" :width="300" :height="300"></f2-canvas>
</view>
</template>
<script>
import F2Canvas from '@/mycomponents/f2-canvas/f2-canvas'
export default {
components: { F2Canvas },
methods: {
onInitChart(F2, config) {
const chart = new F2.Chart(config);
const data = [
{ value: 63.4, city: 'New York', date: '2011-10-01' },
{ value: 62.7, city: 'Alaska', date: '2011-10-01' },
{ value: 72.2, city: 'Austin', date: '2011-10-01' },
{ value: 58, city: 'New York', date: '2011-10-02' },
{ value: 59.9, city: 'Alaska', date: '2011-10-02' },
{ value: 67.7, city: 'Austin', date: '2011-10-02' },
{ value: 53.3, city: 'New York', date: '2011-10-03' },
{ value: 59.1, city: 'Alaska', date: '2011-10-03' },
{ value: 69.4, city: 'Austin', date: '2011-10-03' },
];
chart.source(data, {
date: {
range: [0, 1],
type: 'timeCat',
mask: 'MM-DD'
},
value: {
max: 300,
tickCount: 4
}
});
chart.area().position('date*value').color('city').adjust('stack');
chart.line().position('date*value').color('city').adjust('stack');
chart.render();
// 注意:需要把chart return 出來
return chart;
}
}
}
</script>
運行效果
運行效果