Hone logo
Hone
Problems

Vue Event Handling: Interactive Counter

This challenge focuses on implementing basic event handling in a Vue.js application using TypeScript. You will create a simple interactive counter component that allows users to increment and decrement a numerical value by clicking buttons. This is a fundamental concept in building dynamic and user-friendly web interfaces with Vue.

Problem Description

Your task is to create a Vue.js component named InteractiveCounter. This component should display a number and provide two buttons: one to increase the number and one to decrease it.

Key Requirements:

  1. Display a Number: The component must display a numerical value, initialized to 0.
  2. Increment Button: A button labeled "Increment" must be present. Clicking this button should increase the displayed number by 1.
  3. Decrement Button: A button labeled "Decrement" must be present. Clicking this button should decrease the displayed number by 1.
  4. TypeScript Integration: The component should be written in TypeScript, leveraging Vue's script setup syntax.

Expected Behavior:

When the user clicks the "Increment" button, the displayed number should go up. When the user clicks the "Decrement" button, the displayed number should go down.

Edge Cases to Consider:

  • What happens if the user clicks "Decrement" when the counter is already 0? The counter should be allowed to go into negative numbers.

Examples

Example 1:

Initial State:

<div id="app">
  <interactive-counter></interactive-counter>
</div>

User Interaction:

  1. Clicks "Increment".
  2. Clicks "Increment".
  3. Clicks "Decrement".

Expected Output (in the DOM): The interactive-counter component should display:

1

(after the three clicks)

Example 2:

Initial State:

<div id="app">
  <interactive-counter></interactive-counter>
</div>

User Interaction:

  1. Clicks "Decrement".
  2. Clicks "Decrement".

Expected Output (in the DOM): The interactive-counter component should display:

-2

(after the two clicks)

Constraints

  • The InteractiveCounter component should be a single Vue SFC (.vue file).
  • The solution must use TypeScript for the component's logic.
  • Vue 3 Composition API with <script setup> is the preferred approach.

Notes

  • You will need to manage the state of the counter value within the component.
  • Vue's directive for handling events is @click.
  • Consider how to make the counter value reactive so that changes are reflected in the UI automatically.
  • This challenge focuses on the component's internal logic and presentation. You do not need to worry about integrating it into a larger Vue application for this specific problem.
Loading editor...
typescript