element ui中 :summary-method=“getSummaries“的使用与注释

这段代码展示了如何在HTML的el-table组件中利用JavaScript计算表格数据的汇总,并在表格下方显示合计行。通过遍历columns和data,对数值型列进行求和,对非数值型列显示'N/A',最后将结果返回。模板插槽用于格式化单价和总价,显示带有货币符号的值。
JS部分

getSummaries(param){
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {//只找第一列放合计
            sums[index] = '合计:';
            return;
          }
          const values = data.map(item => Number(item[column.property]));//把对应一列中的之全部取出,放到一个数组中
          if (!values.every(value => isNaN(value))) {//如果el-table-column中没有prop属性,这里的column.property是undefined,所以判断一下values数组是否为空
            sums[index] = values.reduce((prev, curr) => {
              console.log(prev, curr);
              const value = Number(curr);//将values中的每个值转换为number类型
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += '元';
          } else {
            sums[index] = 'N/A';
          }
        });
        return sums;
    }

Html部分

<el-table :data="goodsDate" show-summary :summary-method="getSummaries"  ref="" stripe size="small">
<el-table-column header-align="center" align="left" prop="goodsName" :show-overflow-tooltip="true" label="商品名称"></el-table-column>
         <el-table-column header-align="center" prop="goodsPrice" align="center" label="单价" width="150">
           <template slot-scope="scope">
             <span>¥{{scope.row.goodsPrice | MoneyFormat}}</span>
           </template>
         </el-table-column>
         <el-table-column header-align="center" prop="goodsNum" align="center" label="数量" width="150">
           <template slot-scope="scope">
             <span>{{scope.row.goodsNum}}</span>
           </template>
         </el-table-column>
         <el-table-column header-align="center" prop="goodsAllPrice" align="center" label="总价" width="150">
           <template slot-scope="scope">
             <span>¥{{scope.row.goodsAllPrice | MoneyFormat}}</span>
           </template>
         </el-table-column>
</el-table>

效果图:

<ComboBox x:Name="comboBox1" Foreground="White" FontSize="18" Height="25" Width="260" ItemsSource="{Binding ReagentNameListView}" InputMethod.IsInputMethodEnabled="False" SelectedIndex="{Binding ReagentNameIndex}" IsTextSearchEnabled="False" IsEditable="True" Text="{Binding SearchKeyWord}" IsDropDownOpen="{Binding IsDropDownOpen}" Margin="-1,0" GotFocus="comboBox1_GotFocus" KeyUp="comboBox1_KeyUp" LostFocus="comboBox1_LostFocus"/> XAML代码如上 private void comboBox1_GotFocus(object sender, RoutedEventArgs e) { comboBox1.IsDropDownOpen = true; // 延迟执行,确保 ComboBox 完成焦点处理 Dispatcher.BeginInvoke(new Action(() => { var textBox = FindComboBoxTextBox(comboBox1); if (textBox != null && !string.IsNullOrEmpty(textBox.Text)) { // 将光标置于文本末尾,而不是全选 textBox.CaretIndex = textBox.Text.Length; textBox.SelectionLength = 0; // 不选择任何文本 } }), System.Windows.Threading.DispatcherPriority.Background); } private void comboBox1_KeyUp(object sender, KeyEventArgs e) { comboBox1.IsDropDownOpen = true; } private void comboBox1_LostFocus(object sender, RoutedEventArgs e) { comboBox1.IsDropDownOpen = false; } // 在窗口的代码隐藏类中添加此方法 private TextBox FindComboBoxTextBox(ComboBox comboBox) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(comboBox); i++) { var child = VisualTreeHelper.GetChild(comboBox, i); if (child is TextBox textBox) { return textBox; } else { var descendant = FindVisualChild<TextBox>(child); if (descendant != null) return descendant; } } return null; } // 辅助的递归查找方法 private T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject { if (parent == null) return null; for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++) { var child = VisualTreeHelper.GetChild(parent, i); if (child is T found) return found; else { var descendant = FindVisualChild<T>(child); if (descendant != null) return descendant; } } return null; } 后台.cs代码 public DbReagents DbReagentsInfo { get => _reagentInfo; set => SetProperty(ref _reagentInfo, value); } public ICollectionView ReagentNameListView { get; private set; } public bool IsDropDownOpen { get => _isDropDownOpen; set { if (SetProperty(ref _isDropDownOpen, value)) { if (value) { ReagentNameIndex = -1; } else if (string.IsNullOrWhiteSpace(SearchKeyWord) == false) { CheckAndSelectMatchingItem(); } } } } public int ReagentNameIndex { get => _reagentNameIndex; set { if (SetProperty(ref _reagentNameIndex, value)) { DbReagentsInfo.Name = value > -1 ? ReagentNameListView.OfType<string>().ElementAt(value) : string.Empty; } } } public string SearchKeyWord { get => _searchKeyword; set { if (SetProperty(ref _searchKeyword, value)) { IsDropDownOpen = true; // 防抖处理优化:减少不必要的刷新[10](@ref) _searchDebounceTimer?.Stop(); _searchDebounceTimer?.Start(); } } }/// <summary> /// 检查输入的关键词是否在列表中,如果在则自动选中 /// </summary> private void CheckAndSelectMatchingItem() { _searchDebounceTimer?.Stop(); if (string.IsNullOrWhiteSpace(SearchKeyWord)) { ReagentNameIndex = -1; return; } // 1. 在原始列表中查找匹配项(不区分大小写) var exactMatch = _reagentNameList.FirstOrDefault(item => item.Equals(SearchKeyWord, StringComparison.OrdinalIgnoreCase)); // 2. 如果没有完全匹配的项,可以尝试其他匹配逻辑(如包含匹配) if (exactMatch == null) { // 例如:如果希望部分匹配也能生效,可以取消注释下面的代码 // exactMatch = _reagentNameList.FirstOrDefault(item => // item.IndexOf(SearchKeyWord, StringComparison.OrdinalIgnoreCase) >= 0); // 如果没有找到任何匹配项 if (exactMatch == null) { ReagentNameIndex = -1; return; } } // 3. 在过滤后的视图列表中查找匹配项的索引 var filteredItems = ReagentNameListView.OfType<string>().ToList(); var indexInFilteredView = filteredItems.IndexOf(exactMatch); if (indexInFilteredView >= 0) { // 4. 关键优化:仅在匹配项当前文本不同时才更新SearchKeyWord if (SearchKeyWord != exactMatch) { SearchKeyWord = exactMatch; // 这会自动更新文本框显示 } ReagentNameIndex = indexInFilteredView; } else { ReagentNameIndex = -1; } } private void InitializeCollectionView() { ReagentNameListView = CollectionViewSource.GetDefaultView(_reagentNameList); ReagentNameListView.Filter = item => { if (string.IsNullOrWhiteSpace(_searchKeyword)) return true; return item is string name && name.Contains(_searchKeyword, StringComparison.OrdinalIgnoreCase); }; } private void InitializeSearchDebounceTimer() { _searchDebounceTimer = new System.Windows.Threading.DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) // 适当延长防抖时间[10](@ref) }; _searchDebounceTimer.Tick += OnSearchDebounceTimerTick; } private void OnSearchDebounceTimerTick(object sender, EventArgs e) { _searchDebounceTimer.Stop(); ReagentNameListView?.Refresh(); } ViewModel代码 如上WPF代码实现的功能是:从ComboBox中关键字搜索级选择。帮我看一下代码功能上有何问题,有没有优化的空间?使用户操作更加便捷顺手,请把优化后的方案及代码给我
最新发布
10-29
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值