Salesforce学习 Lwc(十)【lightning-datatable】

2020-12-31 16:19:15 浏览数 (1)

上一篇详细讲解了增删改查的初期数据取得和更新操作,还有一种场景是我们经常遇到的,就是ListView,在Lightning画面中可以创建一些标准ListView,但毕竟标准的东西有自己的限制,这样我们就可以自定义开发,今天主要讲解如何使用Lwc自定义LIstView。

首先我们用到的标签是【lightning-datatable】,然后只要把Title和要显示的项目定义好就行了,【columns】是用来显示Title,【data】是用来显示具体项目的。

例1:基本样式

需要表示的具体数据用ApexClass取得,然后在Js中做好Columns,data。

dreamHouseOpportunityListView.html

代码语言:javascript复制
<template>
  <div style="height: 300px;">
      <lightning-datatable
              key-field="id"
              data={data}
              columns={columns}>
      </lightning-datatable>
  </div>
</template>

dreamHouseOpportunityListView.js

代码语言:javascript复制
import { LightningElement,track } from 'lwc';
import getOpportunityListView from '@salesforce/apex/DreamHouseOpportunityListViewController.getOpportunityListView';
const columns = [
  { label: 'Label', fieldName: 'name' },
  { label: 'AccountName', fieldName: 'accountName', type: 'text' },
  { label: 'ExpectedRevenue', fieldName: 'expectedRevenue', type: 'currency' },
  { label: 'Amount', fieldName: 'amount', type: 'currency' },
  { label: 'CloseDate', fieldName: 'closeDate', type: 'date' },
];
export default class DreamHouseOpportunityListView extends LightningElement {
    @track data = [];
    columns = columns;
    connectedCallback() {
        getOpportunityListView()
        .then(data => {
            this.data = data;
        })
        .catch(error => {
        })
    }
}

DreamHouseOpportunityListViewController.cls

代码语言:javascript复制
public with sharing class DreamHouseOpportunityListViewController {
    @AuraEnabled(cacheable=false)
    public static List<OpportunityWrapper> getOpportunityListView(){
        List<OpportunityWrapper> wappers = new List<OpportunityWrapper>();
        List<Opportunity> resultList = [SELECT Id,Name,Account.name,ExpectedRevenue,Amount,CloseDate
                                        FROM Opportunity];
        if (resultList!=null && resultList.size() > 0) {
            for (Opportunity opp : resultList) {
                OpportunityWrapper wapper = new OpportunityWrapper();
                wapper.id = opp.Id;
                wapper.name = opp.Name;
                wapper.accountName = opp.Account.Name;
                wapper.expectedRevenue = String.valueOf(opp.ExpectedRevenue);
                wapper.amount = String.valueOf(opp.Amount);
                wapper.closeDate = String.valueOf(opp.CloseDate);
                wappers.add(wapper);
            }
        }
        return wappers;
    }
    public class OpportunityWrapper {
        @AuraEnabled
        public String id;
        @AuraEnabled
        public String name;
        @AuraEnabled
        public String accountName;
        @AuraEnabled
        public String expectedRevenue;
        @AuraEnabled
        public String amount;
        @AuraEnabled
        public String closeDate;
    }
}

效果展示:

例2:RowNumber样式

·隐藏CheckBox→hide-checkbox-column

·加上RowNumber→show-row-number-column

代码语言:javascript复制
<template>
  <div style="height: 300px;">
      <lightning-datatable
              key-field="id"
              data={data}
              show-row-number-column
              row-number-offset={rowOffset}
              hide-checkbox-column
              columns={columns}>
      </lightning-datatable>
  </div>
</template>
代码语言:javascript复制
import { LightningElement,track } from 'lwc';
import getOpportunityListView from '@salesforce/apex/DreamHouseOpportunityListViewController.getOpportunityListView';
const columns = [
  { label: 'Label', fieldName: 'name' },
  { label: 'AccountName', fieldName: 'accountName', type: 'text' },
  { label: 'ExpectedRevenue', fieldName: 'expectedRevenue', type: 'currency' },
  { label: 'Amount', fieldName: 'amount', type: 'currency' },
  { label: 'CloseDate', fieldName: 'closeDate', type: 'date' },
];
export default class DreamHouseOpportunityListView extends LightningElement {
    @track data = [];
    columns = columns;
    rowOffset = 0;
    connectedCallback() {
        getOpportunityListView()
        .then(data => {
            this.data = data;
        })
        .catch(error => {
        })
    }
}

效果展示:

例3:RowAction样式

代码语言:javascript复制
<template>
  <div style="height: 300px;">
      <lightning-datatable
              key-field="id"
              data={data}
              columns={columns}
              onrowaction={handleRowAction}>
      </lightning-datatable>
  </div>
  <div class="slds-m-around--medium" style="width: 30rem;">
    <article class="slds-tile">
        <h3 class="slds-tile__title slds-truncate" title="Record details"><a href="javascript:void(0);">Record details</a></h3>
        <div class="slds-tile__detail">
            <dl class="slds-list_horizontal slds-wrap">
                <dt class="slds-item_label slds-text-color_weak slds-truncate" title="Name">Name:</dt>
                <dd class="slds-item_detail slds-truncate">{record.name}</dd>
                <dt class="slds-item_label slds-text-color_weak slds-truncate" title="Balance">Balance:</dt>
                <dd class="slds-item_detail slds-truncate">
                    <lightning-formatted-number value={record.amount} format-style="currency"></lightning-formatted-number>
                </dd>
            </dl>
        </div>
    </article>
</div>
</template>
代码语言:javascript复制
import { LightningElement,track } from 'lwc';
import getOpportunityListView from '@salesforce/apex/DreamHouseOpportunityListViewController.getOpportunityListView';
const actions = [
    { label: 'Show details', name: 'show_details' },
    { label: 'Delete', name: 'delete' },
];
const columns = [
    { label: 'Label', fieldName: 'name' },
    { label: 'AccountName', fieldName: 'accountName', type: 'text' },
    { label: 'ExpectedRevenue', fieldName: 'expectedRevenue', type: 'currency' },
    { label: 'Amount', fieldName: 'amount', type: 'currency' },
    { label: 'CloseDate', fieldName: 'closeDate', type: 'date' },
    {
    type: 'action',
    typeAttributes: { rowActions: actions },
    },
];
export default class DreamHouseOpportunityListView extends LightningElement {
    @track data = [];
    columns = columns;
    record = {};
    connectedCallback() {
        getOpportunityListView()
        .then(data => {
            this.data = data;
        })
        .catch(error => {
        })
    }
    handleRowAction(event) {
        const actionName = event.detail.action.name;
        const row = event.detail.row;
        switch (actionName) {
            case 'delete':
                this.deleteRow(row);
                break;
            case 'show_details':
                this.showRowDetails(row);
                break;
            default:
        }
    }
    deleteRow(row) {
        const { id } = row;
        const index = this.findRowIndexById(id);
        if (index !== -1) {
            this.data = this.data
                .slice(0, index)
                .concat(this.data.slice(index   1));
        }
    }
    findRowIndexById(id) {
        let ret = -1;
        this.data.some((row, index) => {
            if (row.id === id) {
                ret = index;
                return true;
            }
            return false;
        });
        return ret;
    }
    showRowDetails(row) {
        this.record = row;
    }
}

效果展示:

选择Show details,显示当前行数据的详细信息。

例4:InLineEdit样式

代码语言:javascript复制
<template>
  <div style="height: 300px;">
      <lightning-datatable
              key-field="id"
              data={data}
              show-row-number-column
              row-number-offset={rowOffset}
              suppress-bottom-bar
              columns={columns}>
      </lightning-datatable>
  </div>
</template>
代码语言:javascript复制
import { LightningElement,track } from 'lwc';
import getOpportunityListView from '@salesforce/apex/DreamHouseOpportunityListViewController.getOpportunityListView';
const columns = [
    { label: 'Label', fieldName: 'name', editable: true },
    { label: 'AccountName', fieldName: 'accountName', type: 'text', editable: true },
    { label: 'ExpectedRevenue', fieldName: 'expectedRevenue', type: 'currency', editable: true },
    { label: 'Amount', fieldName: 'amount', type: 'currency', editable: true },
    { label: 'CloseDate', fieldName: 'closeDate', type: 'date', editable: true },
];
export default class DreamHouseOpportunityListView1 extends LightningElement {
    @track data = [];
    columns = columns;
    rowOffset = 0;
    connectedCallback() {
        getOpportunityListView()
        .then(data => {
            this.data = data;
        })
        .catch(error => {
        })
    }
}

效果展示:

编辑后

例5:SortableColumn样式

代码语言:javascript复制
<template>
  <lightning-datatable
          key-field="id"
          columns={columns}
          data={data}
          hide-checkbox-column
          default-sort-direction={defaultSortDirection}
          sorted-direction={sortDirection}
          sorted-by={sortedBy}
          onsort={onHandleSort}>
  </lightning-datatable>
</template>
代码语言:javascript复制
import { LightningElement } from 'lwc';
const data = [
  { id: 1, name: 'Billy Simonns', age: 40, email: 'billy@salesforce.com' },
  { id: 2, name: 'Kelsey Denesik', age: 35, email: 'kelsey@salesforce.com' },
  { id: 3, name: 'Kyle Ruecker', age: 50, email: 'kyle@salesforce.com' },
  {
      id: 4,
      name: 'Krystina Kerluke',
      age: 37,
      email: 'krystina@salesforce.com',
  },
];

const columns = [
  { label: 'Name', fieldName: 'name' },
  {
      label: 'Age',
      fieldName: 'age',
      type: 'number',
      sortable: true,
      cellAttributes: { alignment: 'left' },
  },
  { label: 'Email', fieldName: 'email', type: 'email' },
];
export default class DreamHouseOpportunityListView2 extends LightningElement {
    data = data;
    columns = columns;
    defaultSortDirection = 'asc';
    sortDirection = 'asc';
    sortedBy;

    // Used to sort the 'Age' column
    sortBy(field, reverse, primer) {
        const key = primer
            ? function(x) {
                  return primer(x[field]);
              }
            : function(x) {
                  return x[field];
              };

        return function(a, b) {
            a = key(a);
            b = key(b);
            return reverse * ((a > b) - (b > a));
        };
    }

    onHandleSort(event) {
        const { fieldName: sortedBy, sortDirection } = event.detail;
        const cloneData = [...this.data];

        cloneData.sort(this.sortBy(sortedBy, sortDirection === 'asc' ? 1 : -1));
        this.data = cloneData;
        this.sortDirection = sortDirection;
        this.sortedBy = sortedBy;
    }
}

效果展示:

点击Age列,进行排序,升顺↓↓↓

点击Age列,进行排序,降顺↓↓↓

0 人点赞