javascript
import { LightningElement } from 'lwc';
name = 'John'; //
Direct assignment
}
Html
<template>
<p>The name
is: {name}</p>
</template>
Output:
The name is: John
Now we see similar example using getter and setter:
javascript:
import { LightningElement } from 'lwc';
_name = ''; //
Private property for internal use
// Setter for name
set name(value) {
this._name =
value.toUpperCase(); // Modify value before assigning it
}
// Getter for name
get name() {
return
this._name; // Return modified value
}
connectedCallback() {
this.name =
'John'; // Trigger setter
}
}
HTML
<template>
<p>The name
is: {name}</p>
</template>
Result:
The name is: JOHN
Here, the getter and setter add extra control:
·
The setter allows you to manipulate the input
(e.g., convert the name to uppercase).
·
The getter retrieves the manipulated value when
the template requests it.
Advantages
of Using Getters and Setters
Encapsulation: You can hide the internal details of
how data is stored or modified and expose only what is necessary.
Data Transformation: With setters, you can format or
validate input data before saving it. With getters, you can format the output
or return derived properties.
Reactive Behavior: By using setters, you can trigger
additional actions (like updating other properties or firing events) whenever a
property is set.
Example
of a Scenario Without Getters and Setters
In a simpler case where no transformations or logic are
needed, you can directly bind properties in the template without getters and
setters, as shown in the first example. This might be preferred when you just
want to display or store data without any additional processing.
Conclusion
While you can achieve a similar result without getters and
setters, using them provides more control and flexibility, especially when you
need to transform data or implement custom logic.
No comments:
Post a Comment