Commit 59cafe4d by Lin

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

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