在使用wx-f2時遇到了延遲加載問題,網(wǎng)上搜了很久找不到解決方案薛耻。
最主要原因是wx-f2進(jìn)行了更新沸停,使用了微信新版的canvas繪制,而網(wǎng)上大多只是照抄了readme里的內(nèi)容昭卓,或是使用的老版本愤钾。新版本和老版本頁面中主要區(qū)別在于:
1)老版本由于當(dāng)時微信不支持npm install 而將文件夾拷貝到自己項(xiàng)目,并且引入ff-canvas候醒;
新版本直接使用npm構(gòu)建能颁,項(xiàng)目中引入@antv/wx-f2
2)老版本在組件中綁定opts(Object),將初始化函數(shù)作為值放入opts中倒淫,opts: { onInit: initFunction }伙菊;
新版本不再有opts,直接將初始化函數(shù)綁定在onInit上敌土,查看@/antv/wx-f2/index.js中的文件镜硕,發(fā)現(xiàn)在onReady時會觸發(fā)onInit,所以無法做到延遲加載
后來終于在GitHub的issue中找到了類似問題返干,這里可以查看兴枯,我自己也做個整理,方便自己的學(xué)習(xí)矩欠。
1.修改@antv/wx-f2/index.js里的內(nèi)容财剖,請注意使用的版本,我這里是@2.1.1
搜索Component癌淮,定位到組件中的屬性區(qū)域躺坟,修改為以下內(nèi)容
Component({
/**
* 組件的屬性列表
*/
properties: {
onInit: {
type: 'Function',
value: () => {}
},
opts: {
type: Object,
value: {}
}
},
/**
* 組件的初始數(shù)據(jù)
*/
data: {
},
ready() {
// 延時加載不執(zhí)行 onInit
if (this.data.opts.lazyLoad) return
const query = wx.createSelectorQuery().in(this);
query.select('.f2-canvas')
.fields({
node: true,
size: true
})
.exec(res => {
const { node, width, height } = res[0];
const context = node.getContext('2d');
const pixelRatio = wx.getSystemInfoSync().pixelRatio;
// 高清設(shè)置
node.width = width * pixelRatio;
node.height = height * pixelRatio;
const config = { context, width, height, pixelRatio };
const chart = this.data.onInit(F2, config);
if (chart) {
this.chart = chart;
this.canvasEl = chart.get('el');
}
});
},
/**
* 組件的方法列表
*/
methods: {
lazyInit (func) {
const query = wx.createSelectorQuery().in(this);
query.select('.f2-canvas')
.fields({
node: true,
size: true
})
.exec(res => {
const { node, width, height } = res[0];
const context = node.getContext('2d');
const pixelRatio = wx.getSystemInfoSync().pixelRatio;
// 高清設(shè)置
node.width = width * pixelRatio;
node.height = height * pixelRatio;
const config = { context, width, height, pixelRatio };
const chart = func(F2, config);
if (chart) {
this.chart = chart;
this.canvasEl = chart.get('el');
}
});
},
touchStart(e) {
const canvasEl = this.canvasEl;
if (!canvasEl) {
return;
}
canvasEl.dispatchEvent('touchstart', wrapEvent(e));
},
touchMove(e) {
const canvasEl = this.canvasEl;
if (!canvasEl) {
return;
}
canvasEl.dispatchEvent('touchmove', wrapEvent(e));
},
touchEnd(e) {
const canvasEl = this.canvasEl;
if (!canvasEl) {
return;
}
canvasEl.dispatchEvent('touchend', wrapEvent(e));
}
}
});
2.修改wxml文件,去除onInit
<f2 class="f2-chart" opts="{{opts}}" id="f2pie"/>
3.修改js文件乳蓄,即可在異步加載結(jié)束后渲染圖形
Page({
data: {
opts: {
lazyLoad: true // 延遲加載組件
},
chartComponent: null
},
onLoad () {
// 異步獲取數(shù)據(jù)
const self = this;
wx.request({
url: '',
success: function (res) {
let data = res.data;
self.data.chartComponent = self.selectComponent('#f2pie');
self.data.chartComponent.lazyInit((F2, config) => {
const chart = new F2.Chart(config);
chart.source(data);
chart.render();
self.chart = chart;
return chart;
});
}
})
}
}
})