Computer scienceFrontendVue.jsComputable Properties

Watching for changes

Shopping cart

Report a typo

You're developing a simple shopping cart application. You want to update the total price when items are added or removed from the cart. The below code displays a list of items in a shopping cart. Complete the code such that it calculates and displays the total price using a watcher that reacts to changes in the cart items.

Fill in the gaps with the relevant elements
<template>
  <div>
    <ul>
      <li v-for="item in cart" :key="item.id">{{ item.name }} - ${{ item.price }}</li>
    </ul>
    <p>Total: ${{ total }}</p>
  </div>
</template>

<script setup>
import { ref,  } from 'vue'

const cart = ref([
  { id: 1, name: 'Item 1', price: 10 },
  { id: 2, name: 'Item 2', price: 30 }
])

let total = 0

(, (newCart, oldCart) => {
    total = .reduce((acc, item) => acc + item.price, 0)
  },
  {  }
)
total = cart.value.reduce((acc, item) => acc + item.price, 0)
</script>

Create a free account to access the full topic