Update one component (parent), when another is clicked

This is more of a Vue 3 and Typescript question than strictly an Ionic question. Hope you folks may be able to help me.

I am using the split pane, “side menu” starter template for this project: https://github.com/ionic-team/starters/tree/master/vue/official/sidemenu

In my app, the main app.vue which contains this side menu, fetches a list of items from an API when it is mounted and lists the items. This is your “cart” in this app.

Within the router outlet, I am displaying a page menu.vue, which fetches a list of menu items from an api and populates a series of menuItem.vue components for each menu item.

When you click on any menuItem.vue component, it adds itself to your cart via the API. After that API call I need to somehow update the state of the “cart” in app.vue.

In app.vue I have code that looks like this to populate the cart initially.

setup() {
    const cartItems = ref<MenuItem[]>([])

    async function getCartItems() {
      console.log("fetching cart items")
      cartItems.value = await MyAPI.getCart()
    }
    onMounted(() => {
      getCartItems()
    })
    return {
      cartItems,
      getCartItems
    }
  }

It looks as if my end goal is to find a way to trigger getCartItems() again from some kind of event.

My menuItem component looks like this:


ion-card class="menuCard" @click="addToCart">

---

function addToCart() {
            console.log(`${props.menuItem.name} being added to cart`)
            MyAPI.addCartItem(props.menuItem).then(() => {
                // app.vue will need to reset the cart data now.

            })
        }

I don’t know that I really need to maintain any state or anything similar, I just need to re-trigger the getCartItems() function in app.vue. Custom events seem a bit confusing here. Would really appreciate any direction/docs/examples. Thank you!

edit:

Similarly, each item in the “cart” on app.vue is a component, which contains a button to remove that item from the cart via the API. I then need to communicate back up to app.vue to re-fetch the cart data.

if you create a “composable” to manage the cart, you can include the composable in both the menu and in the app vue.

think of the composable as a service that can maintain the state of the cart also.

here is a sample project

3 Likes