Apexからデータを取得する方法
@wire を使用した Apex コール
HTML
<template>
<span class="error999">*****lightning-datatable test-----</span>
<div class="slds-scrollable" style="height: 300px;">
<lightning-datatable
key-field="id"
data={data.data}
row-number-offset={rowOffset}
hide-checkbox-column
columns={columns}>
</lightning-datatable>
</div>
</template>
JS
import { LightningElement, wire } from 'lwc';
import getContacts from '@salesforce/apex/MyContactController.getContacts';
const columns = [
{ label: 'Name', fieldName: 'Name', type: 'text', fixedWidth: null, initialWidth: 50 },
{ label: 'Title', fieldName: 'Title', type: 'text', fixedWidth: null, initialWidth: 100 },
{ label: 'Email', fieldName: 'Email', type: 'text', fixedWidth: null, initialWidth: 150 },
{ label: 'Phone', fieldName: 'Phone', type: 'text', fixedWidth: null, initialWidth: 250 },
];
export default class BasicDatatable extends LightningElement {
//data = [];
columns = columns;
rowOffset = 0;
@wire(getContacts) data;
connectedCallback() {
}
}
Apex
public with sharing class MyContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts() {
return [
SELECT Name, Title, Email, Phone
FROM Contact
LIMIT 10
];
}
}
命令的な Apex コール
htmlはほぼ同じです。
今回はdata={myContacts}に変更します。dataはキーワードようなものなので
<template>
<span class="error999">*****lightning-datatable test-----</span>
<div class="slds-scrollable" style="height: 300px;">
<lightning-datatable
key-field="id"
data={myContacts}
row-number-offset={rowOffset}
hide-checkbox-column
columns={columns}>
</lightning-datatable>
</div>
</template>
注意点:
- wireの場合は、myContacts = []; が不要だったですが、命令の場合は、必須です。
- Apex側は↑のApexコードから 「(cacheable=true)」 を削除します
import { LightningElement, wire } from 'lwc';
import getContacts from '@salesforce/apex/MyContactController.getContacts';
const columns = [
{ label: 'Name', fieldName: 'Name', type: 'text', fixedWidth: null, initialWidth: 50 },
{ label: 'Title', fieldName: 'Title', type: 'text', fixedWidth: null, initialWidth: 100 },
{ label: 'Email', fieldName: 'Email', type: 'text', fixedWidth: null, initialWidth: 150 },
{ label: 'Phone', fieldName: 'Phone', type: 'text', fixedWidth: null, initialWidth: 250 },
];
export default class BasicDatatable extends LightningElement {
myContacts = []; //★★★ 必須です。
columns = columns;
connectedCallback() {
console.log('***connectedCallback start***');
getContacts({ //imperative Apex call
//birthDate: this.minBirthDate
//apex側にパラメータを渡す場合は、ここに
})
.then(result => {
//code to execute if related contacts are returned successfully
console.log('***connectedCallback successfully***');
this.myContacts = result;
console.log('***contacts' + JSON.stringify(result, null, 2));
})
.catch(error => {
console.log('***connectedCallback error error error***');
//code to execute if related contacts are not returned successfully
});
}
}
簡単なテストする場合は、Apexからのデータ取得が不要なので
以下のコードで
this.myContacts = [{"Name":"dataTable","Title":"tttt","Email":"aaa@google.com","phone":"09011112222"}];