vuejs3nuxt3.jsevent-buspass-data

Nuxt3: pass data from page A to B with same level (no relation like child-parent)


iam try use plugins 'mitt' but it not work plugins/mitt.client.js

import mitt from "mitt";
export default defineNuxtPlugin((nuxtApp) => {
  const emitter = mitt();
    nuxtApp.provide('bus', {
      $on: emitter.on,
      $emit: emitter.emit,
    })
  })

cart/index.vue

const handlePassData = ()=>{

  $bus.$emit('itemsToCheckout', 'hello')
  navigateTo('/checkout')
}

checkout/index.vue

onMounted(() => {
console.log($bus);
  $bus.$on('itemsToCheckout', (data)=>{
    itemsToCheckout.value = data
    console.log(data);
  })
});

i cannot receive data on checkout page


Solution

  • The best thing you can do is to introduce state management with Pinia. It can be simply included into Nuxt with a dedicated module.

    In /composables/useCart.js you define the store:

    export const useCart = defineStore('cart', {
      state: () => ({ items: [] }),
      getters: {
        // items will be available as useCart().items out of the box
        // but here you can define additional logic - like compute the total price
      },
      actions: {
        // all methods to manipulate with cart's state 
        // (available as `this` within `actions` scope)
        addToCart(item) {
          this.items.push(item);
        },
      },
    })
    

    then it is available across whole app just via useCart() (thanks to Nuxt autoimports from composables) - first call of this method will initiate the store, then it holds persistent data until the page is refreshed or a special built-in $reset() function is called.