【js】class中constructor如何接收动态值,如timeRange
问题分析
-
Console.vue中定义调用js类PathHeatmapTool,并传递两个参数
tools['path_heatmap'] = new Models.PathHeatmapTool(viewport, props.timeRange); -
PathHeatmapTool构造函数如下:
export class PathHeatmapTool {constructor(view, timeRange) {this.view = view;this.timeRange = timeRange;}enable() {heatmapVisible('path', this.timeRange);}// ... } -
问题:当
props.timeRange在父组件中发生变化时,PathHeatmapTool实例中的this.timeRange不会自动更新。
解决方案
方案1:修改 PathHeatmapTool 类以响应 timeRange 变化(推荐)
修改 src/models/tools/PathHeatmapTool.js 文件:
import { Event } from '../state';
import { heatmapVisible } from '../HeatmapManager';export class PathHeatmapTool {constructor(view, getTimeRange) {this.view = view;// 接收一个函数而不是直接的值,以便始终获取最新值this.getTimeRange = getTimeRange;}enable() {// 调用函数获取最新的 timeRange 值heatmapVisible('path', this.getTimeRange());}disable() {heatmapVisible('noPath');}isSwitch() {return true;}
}
然后在调用时修改初始化方式:
// 将原来的
tools['path_heatmap'] = new Models.PathHeatmapTool(viewport, props.timeRange);// 修改为
tools['path_heatmap'] = new Models.PathHeatmapTool(viewport, () => props.timeRange);
方案2:在 Console.vue 中监听 timeRange 变化并更新热力图
在 [Console.vue](file:///Users/gegewu/projects/sorting_app_2.0/src/views/entry/Console.vue) 中添加一个 watcher:
// 添加对 timeRange 变化的监听
watch(() => props.timeRange,(newTimeRange) => {// 如果热力图工具当前是启用状态,则重新启用以应用新的时间范围if (curTool === 'path_heatmap' && tools['path_heatmap']) {tools['path_heatmap'].enable();}},{ deep: true } // 深度监听数组变化
);
同时修改 [PathHeatmapTool]类以接收新的 timeRange:
import { Event } from '../state';
import { heatmapVisible } from '../HeatmapManager';export class PathHeatmapTool {constructor(view, timeRange) {this.view = view;this.timeRange = timeRange;}// 添加更新 timeRange 的方法updateTimeRange(timeRange) {this.timeRange = timeRange;}enable() {heatmapVisible('path', this.timeRange);}disable() {heatmapVisible('noPath');}isSwitch() {return true;}
}
并在 Console.vue 中更新初始化代码:
tools['path_heatmap'] = new Models.PathHeatmapTool(viewport, props.timeRange);// 添加 watcher
watch(() => props.timeRange,(newTimeRange) => {// 更新工具中的 timeRangeif (tools['path_heatmap']) {tools['path_heatmap'].updateTimeRange(newTimeRange);// 如果工具当前启用,重新启用以应用新时间范围if (curTool === 'path_heatmap') {tools['path_heatmap'].enable();}}},{ deep: true }
);
