-
Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Counter</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/mvp.css" />
<script
defer
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"
></script>
<script>
const data = {
count: 0,
counter() {
console.log(data.count++);
setTimeout(data.counter, 1000);
},
};
</script>
</head>
<body>
<section x-data="data">
<aside x-init="counter">
<p>Count: <span x-text="count"></span></p>
</aside>
</section>
</body>
</html> Goal
ProblemValue of ReasonThere's probably much better ways to implement an automatic incremental counter. This is a simplified model of updating RequestAny help regarding "how to update |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 7 replies
-
X data accepts a function that returns an object. |
Beta Was this translation helpful? Give feedback.
-
Potentially Non-ideal SolutionThis VanillaJS solution is not ideal, unless there is no way to do this in Alpine, in which case it's fine. <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Counter</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/mvp.css" />
<script
defer
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"
></script>
<script>
const data = {
count: 0,
counter() {
console.log(data.count++);
document.querySelector("#count").innerText = data.count; // set innerText
setTimeout(data.counter, 1000);
},
};
</script>
</head>
<body>
<section x-data="data">
<aside x-init="counter">
<p>Count: <span id="count">0</span></p> <!-- set id attribute -->
</aside>
</section>
</body>
</html> |
Beta Was this translation helpful? Give feedback.
-
Ideal Solution<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Counter</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/mvp.css" />
<script
defer
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"
></script>
</head>
<body>
<section>
<aside x-data="data">
<p>Count: <span x-text="count"></span></p>
</aside>
</section>
<script>
const data = {
count: 0,
counter() {
console.log(this.count++);
setTimeout(() => this.counter(), 1000);
},
init() {
this.counter();
},
};
</script>
</body>
</html> CreditSee @ekwoka 's comment above. |
Beta Was this translation helpful? Give feedback.
Ideal Solution