For example, if I can use
@track/@api xyz='stackexchange'
and then access it later in the component directly,
then why would I use something like this,
get xyz {
return 'stackexchange'
}
getter is used in cases where you want to want to do more operations/modify the data. what you do with @track and @api is an assignment. using a getter you can modify the assigned values before passing it over.
Below link will provide you more detail https://lwc.dev/guide/javascript#getters-and-setters
Generally, GET method returns value and SET method sets the value. We will follow the same way as in other OOPS Programming Language, JAVA.
To understand this exercise, we will see when user will give any input in the message box, the same i/p message will be visible in the output as read only.
We have created a Lightning Web Component named “getterSetter“.
<template>
<lightning-card title = "Getter Setter Mechanism" icon-name="utility:bucket">
<lightning-layout>
<lightning-layout-item flexibility="auto" padding="around-small">
<div class="padding-around:small">
<lightning-input label="Message" value={message} onchange={handleMessage}></lightning-input>
</div>
<div class="padding-around:small slds-m-top_small">
<lightning-formatted-text value={outputMessage} ></lightning-formatted-text>
</div>
</lightning-layout-item>
</lightning-layout>
</lightning-card>
</template>
JS -
import { LightningElement, track } from 'lwc';
export default class GetterSetter extends LightningElement {
defaultMsg = "We are learning ";
@track outputMessage;
get message(){
return this.defaultMsg + "Lightning Web Component";
}
set message(val){
this.outputMessage = val;
}
handleMessage(event){
this.message = event.target.value;
}
}
Here, we have declared one private attribute named defaultMsg which will store the default content. We have defined get and set for message property. So, System will return the message as “We are learning Lightning Web Component” and set the message to show in the output layer.Whenever user will write any thing, at this point of time handleMessage(event) function will be invoked, the value of message will be updated.
In the handleMessage(event) function, we have assigned the latest message value to this.message property. When we have assigned message property in this function, set method will be automatically invoked.