Commit 59cafe4d by Lin

fix: 策略分析组件数据传递优化

1 parent e74f3af8
......@@ -55,94 +55,20 @@
</template>
<script>
import { getStrategyOnlineDist } from "@/api/earlyWarningManager";
import noDataImg from "@/assets/strategy/emepty-strategy.png"
export default {
name: 'OnlineOperatorRanking',
props: {
// 开始日期
startDate: {
type: String,
required: true
},
// 结束日期
endDate: {
type: String,
required: true
},
// 业务类型
businessType: {
type: Number,
required: true
// 排行榜数据(由父组件传递)
rankData: {
type: Array,
default: () => []
}
},
data() {
return {
noDataImg,
// 排行榜数据
rankData: [],
// 加载状态
loading: false
noDataImg
};
},
computed: {
// 将日期范围组合成一个计算属性,用于统一监听
dateRange() {
return `${this.startDate}_${this.endDate}`;
}
},
watch: {
// 监听日期范围(组合值),避免 startDate 和 endDate 分别变化时重复调用
dateRange: {
handler() {
this.fetchStrategyOnlineDist();
},
immediate: false
},
businessType: {
handler() {
this.fetchStrategyOnlineDist();
},
immediate: false
}
},
mounted() {
// 调用线上运营分布接口
this.fetchStrategyOnlineDist();
},
methods: {
/**
* 获取线上运营分布
*/
async fetchStrategyOnlineDist() {
this.loading = true;
try {
const params = {
startDate: this.startDate,
endDate: this.endDate,
businessType: this.businessType
};
const res = await getStrategyOnlineDist(params);
if (res) {
this.rankData = res;
}
} catch (error) {
console.error('获取线上运营分布失败:', error);
this.$message.error('获取线上运营分布失败,请稍后重试');
} finally {
this.loading = false;
}
},
/**
* 刷新数据(供外部调用)
*/
refresh() {
this.fetchStrategyOnlineDist();
}
}
};
</script>
......
......@@ -5,7 +5,7 @@
<div class="operator-filter">
线上运营人员:
<el-select
v-model="operatorFilter"
:value="operatorFilter"
size="mini"
style="width: 120px;"
@change="handleOperatorChange"
......@@ -26,7 +26,7 @@
<div class="custom-legend">
<div
class="legend-item"
v-for="(item, index) in pieData"
v-for="(item, index) in processedPieData"
:key="index"
>
<div
......@@ -51,8 +51,6 @@
<script>
import * as echarts from 'echarts';
import { getStrategyTypeDist } from "@/api/earlyWarningManager";
// import { findMerchantStaffList } from '@api/index';
import { merchantStaffByRoleList } from '@api/index';
import noDataImg from "@/assets/strategy/emepty-strategy.png";
......@@ -114,37 +112,27 @@ const transformStrategyData = (apiData) => {
export default {
name: 'StrategyTypeDistribution',
props: {
// 开始日期
startDate: {
type: String,
required: true
// 策略类型分布原始数据(由父组件传递)
pieData: {
type: Array,
default: () => []
},
// 结束日期
endDate: {
type: String,
required: true
},
// 业务类型
businessType: {
type: Number,
required: true
// 运营人员筛选值(双向绑定)
operatorFilter: {
type: [String, Number],
default: null
}
},
data() {
return {
noDataImg,
operatorFilter: null,
myChart: null,
// 运营人员列表
operatorList: [
{ label: '全部', value: null },
],
// 环形图数据(动态从API获取)
pieData: [],
// 加载状态
loading: false,
// 防抖定时器
_operatorChangeTimer: null
// 处理后的图表数据
processedPieData: []
};
},
computed: {
......@@ -152,14 +140,14 @@ export default {
* 图表数据总数
*/
chartTotal() {
return this.pieData.reduce((sum, item) => sum + (item.value || 0), 0);
return this.processedPieData.reduce((sum, item) => sum + (item.value || 0), 0);
},
/**
* 图表是否有数据
*/
hasChartData() {
return this.pieData.length > 0 && this.chartTotal > 0;
return this.processedPieData.length > 0 && this.chartTotal > 0;
},
/**
......@@ -167,29 +155,19 @@ export default {
*/
chartOption() {
return this.getChartOption();
},
/**
* 将日期范围组合成一个计算属性,用于统一监听
*/
dateRange() {
return `${this.startDate}_${this.endDate}`;
},
/**
* 组合所有依赖参数,用于统一监听,避免初始化时重复调用
*/
fetchParams() {
return `${this.startDate}_${this.endDate}_${this.businessType}`;
}
},
watch: {
// 统一监听所有依赖参数的变化,避免重复调用
fetchParams: {
handler() {
this.fetchStrategyTypeDist();
// 监听原始数据变化,处理数据并更新图表
pieData: {
handler(newData) {
this.processedPieData = transformStrategyData(newData);
this.$nextTick(() => {
this.updateChart();
});
},
immediate: true
immediate: true,
deep: true
}
},
mounted() {
......@@ -208,12 +186,6 @@ export default {
// 清理事件监听器
window.removeEventListener('resize', this.resizeChart);
// 清理定时器
if (this._operatorChangeTimer) {
clearTimeout(this._operatorChangeTimer);
this._operatorChangeTimer = null;
}
},
methods: {
/**
......@@ -239,17 +211,11 @@ export default {
},
/**
* 处理运营人员选择变化(添加防抖优化)
* 处理运营人员选择变化
*/
handleOperatorChange(value) {
// 清除之前的定时器
if (this._operatorChangeTimer) {
clearTimeout(this._operatorChangeTimer);
}
// 防抖处理,300ms 后执行
this._operatorChangeTimer = setTimeout(() => {
this.fetchStrategyTypeDist();
}, 300);
// 通过 .sync 修饰符自动更新父组件的值
this.$emit('update:operatorFilter', value);
},
/**
......@@ -303,7 +269,7 @@ export default {
labelLine: {
show: false
},
data: this.pieData.map(item => ({
data: this.processedPieData.map(item => ({
value: item.value,
name: item.name,
itemStyle: { color: item.color }
......@@ -350,46 +316,6 @@ export default {
}
},
/**
* 获取策略类型分布(优化版)
*/
async fetchStrategyTypeDist() {
this.loading = true;
try {
const params = {
startDate: this.startDate,
endDate: this.endDate,
businessType: this.businessType,
uuid: this.operatorFilter
};
const res = await getStrategyTypeDist(params);
// 使用工具函数转换数据
this.pieData = transformStrategyData(res);
// 更新图表
this.$nextTick(() => {
this.updateChart();
});
} catch (error) {
console.error('获取策略类型分布失败:', error);
this.$message.error('获取策略类型分布失败,请稍后重试');
this.pieData = [];
this.updateChart();
} finally {
this.loading = false;
}
},
/**
* 刷新数据(供外部调用)
*/
refresh() {
this.fetchStrategyTypeDist();
}
}
};
</script>
......
......@@ -50,9 +50,8 @@
<el-col :span="12">
<strategy-type-chart
ref="strategyTypeChart"
:start-date="startDate"
:end-date="endDate"
:business-type="currentTab.value"
:pie-data="strategyTypeData"
:operator-filter.sync="strategyTypeOperatorFilter"
/>
</el-col>
......@@ -60,9 +59,7 @@
<el-col :span="12">
<online-oper-list
ref="onlineOperList"
:start-date="startDate"
:end-date="endDate"
:business-type="currentTab.value"
:rank-data="onlineOperData"
/>
</el-col>
</el-row>
......@@ -163,7 +160,7 @@ import SelectCustom from '../strategyCentre/compoments/selectCustom.vue';
import calendarCustom from '../strategyCentre/compoments/clendarCustom.vue';
import StrategyTypeChart from './components/StrategyTypeChart/index.vue';
import OnlineOperList from './components/OnlineOperList';
import { getStrategyTotal, getMonitorTypeDictList, getStrategyEffectList } from "@/api/earlyWarningManager";
import { getStrategyTotal, getMonitorTypeDictList, getStrategyEffectList, getStrategyTypeDist, getStrategyOnlineDist } from "@/api/earlyWarningManager";
import { deepClone } from "@/common/util";
import dayjs from 'dayjs';
import noDataImg from "@/assets/strategy/emepty-strategy.png"
......@@ -220,8 +217,16 @@ export default {
endDate: dayjs().format('YYYY-MM-DD') + ' 23:59:59',
// 加载状态
loading: {
kpiData: false
kpiData: false,
strategyTypeData: false,
onlineOperData: false
},
// 策略类型分布数据
strategyTypeData: [],
// 线上运营分布数据
onlineOperData: [],
// 策略类型分布筛选的运营人员UUID
strategyTypeOperatorFilter: null,
// 存储原始监控类型数据(接口返回的完整数据)
monitorTypeData: [],
// 当前选中的盯防类型
......@@ -233,6 +238,8 @@ export default {
getListApi: null, // 在 mounted 中初始化
// 初始化标志,用于避免初始化阶段 watch 触发重复刷新
isInitializing: false,
// 策略类型分布运营人员筛选防抖定时器
_strategyTypeOperatorTimer: null,
tableParams: {
listName: "data",
tableColumns: [
......@@ -355,6 +362,16 @@ export default {
}
},
watch: {
// 监听业务类型变化,重新获取数据
'currentTab.value'(newValue, oldValue) {
if (newValue !== oldValue && oldValue !== undefined) {
this.fetchStrategyTotal();
this.fetchStrategyTypeDist();
this.fetchStrategyOnlineDist();
// 重置运营人员筛选
this.strategyTypeOperatorFilter = null;
}
},
// 监听盯防类型变化,自动选择第一个指标类型
'currentWatchType.value'(newValue, oldValue) {
if (newValue !== oldValue) {
......@@ -385,6 +402,18 @@ export default {
// 只在非初始化阶段才刷新表格数据
this.$refs.table && this.$refs.table.refreshTable();
}
},
// 监听策略类型分布运营人员筛选变化,防抖请求数据
strategyTypeOperatorFilter(newValue, oldValue) {
if (newValue !== oldValue && oldValue !== undefined) {
// 防抖处理,300ms 后执行
if (this._strategyTypeOperatorTimer) {
clearTimeout(this._strategyTypeOperatorTimer);
}
this._strategyTypeOperatorTimer = setTimeout(() => {
this.fetchStrategyTypeDist();
}, 300);
}
}
},
mounted() {
......@@ -394,10 +423,18 @@ export default {
this.enablePageScroll();
// 调用策略总数接口
this.fetchStrategyTotal();
// 调用策略类型分布和线上运营分布接口
this.fetchStrategyTypeDist();
this.fetchStrategyOnlineDist();
},
beforeDestroy() {
// 禁用页面滚动
this.disablePageScroll();
// 清理定时器
if (this._strategyTypeOperatorTimer) {
clearTimeout(this._strategyTypeOperatorTimer);
this._strategyTypeOperatorTimer = null;
}
},
methods: {
/**
......@@ -643,14 +680,8 @@ export default {
// 重新获取数据
this.fetchStrategyTotal();
// 刷新策略类型分布组件
if (this.$refs.strategyTypeChart) {
this.$refs.strategyTypeChart.refresh();
}
// 刷新线上运营分布组件
if (this.$refs.onlineOperList) {
this.$refs.onlineOperList.refresh();
}
this.fetchStrategyTypeDist();
this.fetchStrategyOnlineDist();
// 刷新表格数据
this.$refs.table && this.$refs.table.refreshTable();
},
......@@ -658,7 +689,6 @@ export default {
* 处理时间范围类型变化
*/
handleTimeRangeChange(type, dateRange) {
console.log('时间范围类型变化:', type, dateRange);
// 更新时间范围类型
if (typeof type === 'string') {
......@@ -681,7 +711,50 @@ export default {
handleDateRangeChange(dateRange) {
console.log('日期范围变化:', dateRange);
this._updateDateRangeAndRefresh(dateRange);
}
},
/**
* 获取策略类型分布
*/
async fetchStrategyTypeDist() {
this.loading.strategyTypeData = true;
try {
const params = {
startDate: this.startDate,
endDate: this.endDate,
businessType: this.currentTab.value,
uuid: this.strategyTypeOperatorFilter
};
const res = await getStrategyTypeDist(params);
this.strategyTypeData = res || [];
} catch (error) {
console.error('获取策略类型分布失败:', error);
this.$message.error('获取策略类型分布失败,请稍后重试');
this.strategyTypeData = [];
} finally {
this.loading.strategyTypeData = false;
}
},
/**
* 获取线上运营分布
*/
async fetchStrategyOnlineDist() {
this.loading.onlineOperData = true;
try {
const params = {
startDate: this.startDate,
endDate: this.endDate,
businessType: this.currentTab.value
};
const res = await getStrategyOnlineDist(params);
this.onlineOperData = res || [];
} catch (error) {
console.error('获取线上运营分布失败:', error);
this.$message.error('获取线上运营分布失败,请稍后重试');
this.onlineOperData = [];
} finally {
this.loading.onlineOperData = false;
}
},
}
};
</script>
......
  • @limin
    commented
    Owner

    你好,我是负责本次代码审查的软件开发工程师。你对 strategyAnalysis 模块进行了“状态提升(Lifting State Up)”的重构,将数据获取逻辑从子组件移动到了父组件,这是一个符合 React/Vue 单向数据流最佳实践的改动,有助于统一管理数据源和减少重复请求。

    但在审查中,我发现了组件生命周期时序、冗余请求以及用户体验(UX)方面的几个关键问题。

    以下是具体的审查报告:

    一、关键问题与优化建议(Top 3)

    1. StrategyTypeChart 组件存在渲染时序 Bug,可能导致图表初始化空白

    • 问题描述:在 StrategyTypeChart/index.vue 中,你使用了 watch: { pieData: { immediate: true } } 来监听数据变化并更新图表。然而,immediate: true 的回调会在组件 created 钩子之前执行,此时 mounted 尚未执行,this.myChart 实例还未初始化(为 null)。
    • 影响分析:如果父组件传入的 pieData 在组件挂载前就有数据(例如:组件被缓存或父组件数据已存在),updateChart 会因为 !this.myChart 而直接返回。随后 mounted 执行并初始化了图表实例,但没有再次调用渲染逻辑,导致图表显示为空白,直到下一次数据变更。
    • 优化建议:在 mounted 生命周期中,初始化图表实例后,显式调用一次 updateChart(或者在该方法内判断是否有数据需要渲染)。
    // src/views/earlyWarningManager/strategyAnalysis/components/StrategyTypeChart/index.vue
    
    mounted() {
      this.$nextTick(() => {
        this.initChart();
        // 修复:初始化后立即尝试渲染,确保初始数据能被绘制
        if (this.processedPieData && this.processedPieData.length > 0) {
          this.updateChart();
        }
        window.addEventListener('resize', this.resizeChart);
      });
    },
    

    2. index.vue 切换业务类型时存在冗余的 API 请求(Race Condition)

    • 问题描述:在 index.vue 的 currentTab.value 监听器中,你同时执行了 this.fetchStrategyTypeDist() 和 this.strategyTypeOperatorFilter = null。
      • 动作 1:fetchStrategyTypeDist() 使用当前的筛选值(可能是旧值)发起了第 1 次请求。
      • 动作 2:strategyTypeOperatorFilter = null 触发了该变量的 watch,防抖后会发起第 2 次请求(使用 null 值)。
    • 影响分析:每次切换 Tab 都会触发两次几乎同时的请求。这不仅浪费服务器资源,还可能因为网络响应顺序的不确定性(Race Condition),导致最终显示的图表数据与筛选状态不一致(例如第 1 次请求晚于第 2 次请求返回)。
    • 优化建议:在切换 Tab 时,仅重置筛选条件,利用筛选条件的 watch 来驱动数据获取;或者在重置前判断值是否变化。
    // src/views/earlyWarningManager/strategyAnalysis/index.vue
    
    watch: {
      'currentTab.value'(newValue, oldValue) {
        if (newValue !== oldValue && oldValue !== undefined) {
          this.fetchStrategyTotal();
          this.fetchStrategyOnlineDist();
    
          // 优化:
          // 如果当前有筛选值,重置它会触发 strategyTypeOperatorFilter 的 watcher 从而自动请求数据
          if (this.strategyTypeOperatorFilter) {
            this.strategyTypeOperatorFilter = null; 
          } else {
            // 如果原本就是 null,则 watcher 不会触发,需要手动请求
            this.fetchStrategyTypeDist();
          }
        }
      },
      // ...
    }
    

    3. 丢失 Loading 状态反馈,降低用户体验

    • 问题描述:重构前,子组件内部维护了 loading 状态并展示加载效果。重构后,父组件 index.vue 虽然维护了 loading.strategyTypeData 等状态,但并没有通过 props 传递给子组件(StrategyTypeChart 和 OnlineOperList),且子组件内部删除了 loading 相关的 UI 逻辑。
    • 影响分析:在网络请求期间,用户将看到旧数据或空白区域,没有任何加载中的提示,这属于明显的用户体验退化。
    • 优化建议:在子组件中恢复 v-loading 支持,并从父组件传入 loading 状态。
    <!-- 父组件 index.vue -->
    <strategy-type-chart
      ref="strategyTypeChart"
      :pie-data="strategyTypeData"
      :operator-filter.sync="strategyTypeOperatorFilter"
      v-loading="loading.strategyTypeData" <!-- 建议添加 -->
    />
    

    二、评分明细

    1. 功能实现的正确性与健壮性(32/40)

      • 扣分项:图表初始化时序 Bug(Issue 1)可能导致图表不显示;Tab 切换时的竞态请求(Issue 2)可能导致数据不一致。
      • 优点:状态提升的逻辑方向正确,数据流更清晰。
    2. 安全性与潜在风险(30/30)

      • 未发现明显的 XSS 或注入风险,参数传递符合规范。
    3. 最佳实践与可维护性(15/20)

      • 扣分项:丢失了 Loading 状态反馈(Issue 3);组件间通信使用了 .sync 修饰符是 Vue 2 的推荐做法,这部分做得很好。
      • 建议:StrategyTypeChart 中对 pieData 开启了 deep: true 监听,如果数据量极大可能会有性能损耗,但在图表场景下通常可接受。
    4. 性能与资源利用(4/5)

      • 扣分项:Tab 切换时的重复请求造成了轻微的资源浪费。
    5. 提交信息质量(5/5)

      • Commit 信息 "fix: 策略分析组件数据传递优化" 清晰明了。

    三、总分

    总分:86分

Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!