Hone logo
Hone
Problems

Vue Component Getters: Dynamic Data Transformation

Vue.js offers powerful reactivity features, and understanding how to leverage them is crucial for building dynamic and maintainable applications. This challenge focuses on implementing getters within a Vue component using TypeScript. Getters allow you to compute derived state based on existing data, making your component logic cleaner and more efficient.

Problem Description

Your task is to create a Vue 3 component that displays a list of products, each with a name and a price. You need to implement a getter that calculates the total price of all products in the list. This total price should update automatically whenever the product list changes (e.g., a product is added, removed, or its price is modified).

Key Requirements:

  • Create a Vue 3 component using TypeScript.
  • The component should manage a reactive array of Product objects.
  • Implement a getter function that calculates the sum of all product prices.
  • The getter's output should be displayed in the component's template.
  • The displayed total price must update reactively as the product list changes.

Expected Behavior:

When the component loads, it should display the initial list of products and their calculated total price. If you were to programmatically add a new product to the list, the total price displayed should immediately reflect the new sum.

Important Considerations:

  • Ensure the Product interface is defined.
  • The getter should be efficiently computed and only recalculated when its dependencies change.

Examples

Example 1:

Initial Product List:
[
  { id: 1, name: "Laptop", price: 1200 },
  { id: 2, name: "Mouse", price: 25 }
]

Output Displayed:

Products:
- Laptop: $1200
- Mouse: $25
Total Price: $1225

Explanation: The getter correctly sums the prices of the initial products.

Example 2:

After adding a new product:
Product List:
[
  { id: 1, name: "Laptop", price: 1200 },
  { id: 2, name: "Mouse", price: 25 },
  { id: 3, name: "Keyboard", price: 75 }
]

Output Displayed:

Products:
- Laptop: $1200
- Mouse: $25
- Keyboard: $75
Total Price: $1300

Explanation: The getter has automatically recalculated and updated the total price after a new product was added to the reactive list.

Constraints

  • The Product interface should have at least id (number), name (string), and price (number) properties.
  • You will be working with Vue 3 Composition API and TypeScript.
  • The solution should be performant; avoid unnecessary recalculations.

Notes

  • Think about how Vue's reactivity system works with computed properties.
  • Consider using ref or reactive for managing the product list.
  • The computed function from Vue is your primary tool for implementing getters.
  • Formatting the currency display is optional but good practice.
Loading editor...
typescript