Hone logo
Hone
Problems

Vue Component State Management: A Simple Counter

This challenge focuses on a fundamental aspect of building interactive web applications with Vue.js: managing component state. You will implement a basic counter component that allows users to increment and decrement a numerical value, demonstrating how to store and update data within a Vue component. This is a crucial skill for building any dynamic user interface.

Problem Description

Your task is to create a Vue.js component, written in TypeScript, that displays a counter. The component should have the following functionalities:

  • Display Current Count: Show the current numerical value of the counter.
  • Increment Button: A button that, when clicked, increases the counter by 1.
  • Decrement Button: A button that, when clicked, decreases the counter by 1.

Key Requirements:

  • The component must be written using Vue 3 Composition API and TypeScript.
  • The counter's value should be stored as reactive state within the component.
  • The buttons must trigger updates to this reactive state.
  • The displayed count should automatically update whenever the state changes.

Expected Behavior:

When the component is rendered, it should display an initial count (e.g., 0). Clicking the "Increment" button will increase the displayed number, and clicking the "Decrement" button will decrease it.

Edge Cases:

  • Consider what happens if the counter reaches zero and the decrement button is pressed. For this challenge, you do not need to implement any specific logic to prevent the counter from going below zero, but be aware of this potential behavior.

Examples

Example 1:

Initial Render:

<div class="counter-component">
  <p>Count: 0</p>
  <button>Increment</button>
  <button>Decrement</button>
</div>

After clicking "Increment" once:

<div class="counter-component">
  <p>Count: 1</p>
  <button>Increment</button>
  <button>Decrement</button>
</div>

After clicking "Decrement" twice from the initial state:

<div class="counter-component">
  <p>Count: -2</p>
  <button>Increment</button>
  <button>Decrement</button>
</div>

Constraints

  • The counter value should be an integer.
  • The component should be designed to be reusable.
  • Performance is not a primary concern for this basic challenge, but aim for clean and efficient state management.

Notes

  • You will need to use Vue's ref function from the Composition API to create reactive state.
  • Event handling for button clicks will be crucial.
  • Think about how to bind the reactive state to the template for display.
  • Consider the separation of concerns: template for UI, script for logic.
Loading editor...
typescript