繁体   English   中英

ag-grid vue.js:如何在打字稿中访问渲染器的父网格方法?

[英]ag-grid vue.js: How to access to the parent grid method of a renderer in typescript?

我在一个项目中使用ag-grid,在其中添加了特殊的单元格渲染器: https : //www.ag-grid.com/javascript-grid-cell-rendering-components/#example-rendering-using-vuejs-components

渲染器工作正常,除了我无法访问上面给出的示例中的父网格方法(即this.params.context.componentParent.methodFromParent(...);

负责自定义单元格渲染和交互的单元格渲染器:

模板=> ActionCellRenderer.vue

<template>
    <span v-if="isPending() && !isConfirmed">
        <v-btn v-if="!isAskingForConfirmation"
               v-on:click="askForConfirmation"
               depressed small
               class="button">
            <v-icon class="icon">undo</v-icon> Cancel
        </v-btn>

        <v-btn v-else
               v-on:click="confirm"
               depressed small
               class="button" >
            <v-icon class="icon">error_outline</v-icon> Are you sure?
        </v-btn>
    </span>
</template>

<style>
    .button {
        margin: 0;
        font-size: .72rem;
    }

    .icon {
        font-size: 1.3rem;
    }
</style>

<script lang="ts" src="./ActionCellRenderer.ts">
</script>

逻辑=> ActionCellRenderer.ts

@Component
export default class ActionCellRenderer extends Vue {

    public isAskingForConfirmation = false;
    public isConfirmed = false;

    isPending(): boolean {
        // @ts-ignore
        return this.params.value === "Pending";
    }

    askForConfirmation(): void {
        // @ts-ignore
        this.isAskingForConfirmation = true;
        // @ts-ignore
        console.log(this.params);
        window.setTimeout(()  => {
            this.isAskingForConfirmation = false;
        }, 3000);
    }

    confirm(): void {
        alert("Confirmed!");
        this.isConfirmed = true;
    }
}

父网格:

模板=> CashoutRecords.vue

<template>
  <ag-grid-vue
    class="ag-theme-balham"
    domLayout="autoHeight"
    :columnDefs="columnDefs"
    :defaultColDef="defaultColDef"
    :frameworkComponents="frameworkComponents"
    :rowData="cashoutRecords"
:gridOptions="gridOptions"
@grid-ready="onGridReady"
></ag-grid-vue>
</template>

<style>
  .ag-row .ag-cell {
    display: flex;
    align-items: center;
  }
</style>

<script lang="ts" src="./CashoutRecords.ts">
</script>

逻辑=> CashoutRecords.ts

@Component({
    components: {
        AgGridVue,
    },
})
export default class CashoutRecords extends Vue {

    @NS.Action(Actions.fetchCashouts) fetchCashouts!: ActionTypes.fetchCashouts;
    @NS.Action(Actions.fetchCompanies) fetchCompanies!: ActionTypes.fetchCompanies;
    @NS.Getter(Getters.cashoutRecords) cashoutRecords!: GetterTypes.cashoutRecords;

    gridOptions: GridOptions = {
        rowHeight: 45,
    };

    frameworkComponents = {
        actionCellRenderer: ActionCellRenderer,
    };

    columnDefs: ColDef[] = [
        {
            headerName: "",
            filter: true,
            pinned: "right",
            field: "state.name",
            width: 130,
            resizable: true,
            cellRenderer: "actionCellRenderer",
        },
        { headerName: "Date", field: "createdOn", valueFormatter: this.dateTimeFormatter, width: 150, resizable: true },
        { headerName: "Recipient", field: "recipient", resizable: true },
        { headerName: "Amount", field: "amount", valueFormatter: this.currencyFormatter, width: 110, resizable: true },
        { headerName: "Label", field: "comment", resizable: true },
        { headerName: "State", field: "state.name", width: 100, resizable: true },
        { headerName: "Created by", field: "createdBy", resizable: true },
    ];

    defaultColDef = { filter: true };

    private gridApi!: GridApi;

    mounted() {
        if (this.gridOptions.api) {
            this.gridApi = this.gridOptions.api;
        }
    }

    async onGridReady() {
        await this.loadCashoutRecords();
    }

    async loadCashoutRecords() {
        this.gridApi.showLoadingOverlay();
        await Promise.all([
            this.fetchCompanies(),
            this.fetchCashouts(),
        ]);
        if (this.cashoutRecords.length === 0) {
            this.gridApi.showNoRowsOverlay();
        } else {
            this.gridApi.hideOverlay();
        }
    }

    private methodFromParent(cell: any) {
        alert("Parent Component Method from " + cell + "!");
    }

    private currencyFormatter(params: ValueFormatterParams) {
        return toCurrency(params.value);
    }

    private dateTimeFormatter(params: ValueFormatterParams) {
        return toDateTime(params.value);
    }
}

当做console.log(this.params); 调用askForConfirmation方法时,我看不到任何context字段:

Object
$scope = null
addRenderedRowListener = function (eventType, listener) {
addRowCompListener = function () { [native code] }
agGridReact = Object {}
api = GridApi {detailGridInfoMap: , immutableService: , csvCreator: , excelCreator: , gridCore: , ...}
column = Column {moving: false, menuVisible: false, filterActive: false, eventService: , rowGroupActive: false, ...}
columnApi = ColumnApi {columnController: }
colDef = Object {filter: true, headerName: "", pinned: "right", field: "state.name", width: 130, ...}
data = Object {id: 3, recipientAccountId: 456, recipientAccountName: "Samuel L. Jackson", createdOn: "2019-06-10T17:02:00", amount: 666, ...}
eGridCell = div.ag-cell.ag-cell-not-inline-editing.ag-cell-with-height.ag-cell-first-right-pinned.ag-cell-value.ag-column-hover.ag-cell-focus {__AG_0.44240488142399337: , align: "", title: "", lang: "", translate: true, ...}
eParentOfValue = div.ag-cell.ag-cell-not-inline-editing.ag-cell-with-height.ag-cell-first-right-pinned.ag-cell-value.ag-column-hover.ag-cell-focus {__AG_0.44240488142399337: , align: "", title: "", lang: "", translate: true, ...}
formatValue = function () { [native code] }
frameworkComponentWrapper = VueFrameworkComponentWrapper {parent: }
getValue = function () { [native code] }
node = RowNode {childrenMapped: , selectable: true, alreadyRendered: true, selected: false, mainEventService: , ...}
allChildrenCount = null
alreadyRendered = true
canFlower = false
childrenAfterFilter = undefined
childrenMapped = Object {}
childIndex = 2
columnApi = ColumnApi {columnController: }
columnController = ColumnController {primaryHeaderRowCount: 1, secondaryHeaderRowCount: 0, secondaryColumnsPresent: false, gridHeaderRowCount: 1, displayedLeftColumns: , ...}
context = Context {beans: , componentsMappedByName: , destroyed: false, contextParams: , logger: }
data = Object {id: 3, recipientAccountId: 456, recipientAccountName: "Samuel L. Jackson", createdOn: "2019-06-10T17:02:00", amount: 666, ...}
eventService = EventService {allSyncListeners: , allAsyncListeners: , globalSyncListeners: , globalAsyncListeners: , asyncFunctionsQueue: , ...}
expanded = false
firstChild = false
gridApi = GridApi {detailGridInfoMap: , immutableService: , csvCreator: , excelCreator: , gridCore: , ...}
gridOptionsWrapper = GridOptionsWrapper {propertyEventService: , domDataKey: "__AG_0.44240488142399337", layoutElements: , gridOptions: , columnController: , ...}
group = false
id = "2"
lastChild = false
level = 0
mainEventService = EventService {allSyncListeners: , allAsyncListeners: , globalSyncListeners: , globalAsyncListeners: , asyncFunctionsQueue: , ...}
master = false
oldRowTop = undefined
rowHeight = 45
rowIndex = 2
rowModel = ClientSideRowModel {gridOptionsWrapper: , columnController: , filterManager: , $scope: undefined, selectionController: , ...}
rowTop = 90
selectable = true
selected = false
selectionController = SelectionController {eventService: , rowModel: , gridOptionsWrapper: , columnApi: , gridApi: , ...}
uiLevel = 0
valueCache = ValueCache {cacheVersion: 1, gridOptionsWrapper: , active: false, neverExpires: false}
valueService = ValueService {initialised: true, gridOptionsWrapper: , expressionService: , columnController: , eventService: , ...}
__proto__ = Object {setData: , updateDataOnDetailNode: , createDataChangedEvent: , createLocalRowEvent: , updateData: , ...}
refreshCell = function () { [native code] }
rowIndex = 2
setValue = function (value) {
value = "Pending"
valueFormatted = null
__proto__ = Object {constructor: , __defineGetter__: , __defineSetter__: , hasOwnProperty: , __lookupGetter__: , ...}

如何从单元格渲染器访问网格方法methodFromParent

好吧,这很简单,我只是忘了声明一个contextmethods字段(出于某些原因,我认为这是内置的...)。

长话短说:

逻辑=> CashoutRecords.ts

context = { componentParent: this };
methods = {
    async methodFromParent(cell: any) {
        // ... implementation goes here
    }
};

并在模板中添加对该上下文的引用:

模板=> CashoutRecords.vue

<template>
  <ag-grid-vue
    ...
    :context="context"
...
></ag-grid-vue>
</template>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM