Created
March 6, 2024 17:28
-
-
Save kristoferjoseph/56050518f6b94ca7754666664662da60 to your computer and use it in GitHub Desktop.
Counter component using Enhance element and attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<title></title> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
</head> | |
<body> | |
<my-counter count=5></my-counter> | |
<script type="module"> | |
import enhance from "https://unpkg.com/@enhance/[email protected]/dist/index.js?module=true"; | |
enhance("my-counter", { | |
attrs: ['count'], | |
render({ html, state }) { | |
const { attrs = {} } = state; | |
const { count = 0 } = attrs; | |
// render the input with a count value from the store | |
return html` | |
<input value="${count}" /> | |
<button aria-label="decrement">-</button> | |
<button aria-label="increment">+</button> | |
`; | |
}, | |
connected() { | |
// Use the count attribute to set the starting count per instance | |
this.count = Number(this.getAttribute("count")) | |
this.increment = this.querySelector('[aria-label=increment]') | |
this.increment.addEventListener('click', e => { | |
this.count = this.count + 1 | |
this.setAttribute('count', this.count) | |
}) | |
this.decrement = this.querySelector('[aria-label=decrement]') | |
this.decrement.addEventListener('click', e => { | |
this.count = this.count - 1 | |
this.setAttribute('count', this.count) | |
}) | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This example demonstrates how to use attributes and state to enable data reactivity with a single element.