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:
- Display a Number: The component must display a numerical value, initialized to
0. - Increment Button: A button labeled "Increment" must be present. Clicking this button should increase the displayed number by
1. - Decrement Button: A button labeled "Decrement" must be present. Clicking this button should decrease the displayed number by
1. - 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:
- Clicks "Increment".
- Clicks "Increment".
- 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:
- Clicks "Decrement".
- Clicks "Decrement".
Expected Output (in the DOM):
The interactive-counter component should display:
-2
(after the two clicks)
Constraints
- The
InteractiveCountercomponent should be a single Vue SFC (.vuefile). - 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.