Lit introduces a set of render lifecycle callback methods on top of the native web component callbacks. These callbacks are triggered when declared Lit reactive properties are changed.
To use this feature, you must statically declare which properties are Reactive Properties – properties that will trigger the render lifecycle when changed:
// remove observedAttributes() and attributeChangedCallback()
// remove set rating() get rating()
// remove set vote() get vote()
// remove the _rating and _vote private class members
...
exportclassRatingElementextendsLitElement {
...
staticproperties = {
rating: {type: Number},
vote: {type: String, reflect: true},
};
constructor() {
super();
this.rating=0;
this.vote=null;
}
// remove observedAttributes() and attributeChangedCallback()
// remove set rating() get rating()
// remove set vote() get vote()
// remove the _rating and _vote private class members
...
Here, you:
Declare that rating and vote are reactive properties.
They will trigger the LitElement rendering lifecycle when changed.
Define the type that will be used to convert the string attributes into properties.
Remove setter and getter logic for the reactive properties.
Remove the attribute handling logic.
Clean up some unnecessary private class members.
Pass complex objects as properties.
It is generally good practice to pass complex objects as properties rather than attributes. Read more on reactive property attribute conversion in the Lit documentation.
Additionally, the reflect flag on the vote property will automatically update the host element's voteattribute that you formerly updated in the vote setter. It is necessary to reflect the vote attribute so the :host([vote=up]) styles can be applied.
The logic here is the same from the vote setter logic just moved to to the willUpdate() lifecycle method.
The willUpdate() method is called before render() every time a reactive property is changed. Because LitElement batches property changes and makes rendering asynchronous, changes to reactive properties (like this.rating) in willUpdate() will not trigger unnecessary render lifecycle calls.
Congratulations, you should have a working Lit Element!