ag-grid vue.js: Как получить доступ к методу родительской сетки рендерера в машинописи? - PullRequest
1 голос
/ 26 июня 2019

Я использую ag-grid в проекте, где я добавляю специальный рендерер ячеек: https://www.ag -grid.com / javascript-grid-cell-render-components / # example-render-using-vuejs-компоненты

Средство визуализации работает нормально, за исключением того, что я не могу получить доступ к методам родительской сетки, как в примере, приведенном выше (т. е. this.params.context.componentParent.methodFromParent(...);)

Средство визуализации ячеек, отвечающее за настройкурендеринг ячейки и взаимодействия:

Template => 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>

Logic => 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;
    }
}

Родительская сетка:

Template => 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>

Logic => 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 из средства визуализации ячеек?

1 Ответ

0 голосов
/ 27 июня 2019

Хорошо, это было довольно просто, я просто забыл объявить поля context и methods (по некоторым причинам я думал, что они были встроенными ...).

Короче говоря:

Logic => CashoutRecords.ts:

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

И добавить ссылку на этот контекст в шаблон:

Template => CashoutRecords.vue:

<template>
  <ag-grid-vue
    ...
    :context="context"
...
></ag-grid-vue>
</template>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...