vue.jsroutesvue-props

How to pass data (array and number in this case) as a prop to another route in vue?


So i have a routing set up in my Vue application and i have a HomeView view and a CheckoutView view and i want to pass the data as a prop from HomeView ("/") to CheckoutView ("/checkout") but i cant find a way to do it since they have no connections. To be exact, i want to send the cart array and total value from HomeView to CheckoutView everytime user requests "/checkout" route.

router/index.js

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
  },
  {
    path: '/checkout',
    name: 'checkout',
    component: () => import('../views/CheckoutView.vue')
  }
]

HomeView.vue

export default {
import productsData from '@/assets/products.json';

  name: 'HomeView',
  data() {
    return {
      products: [],
      cart: [],
      total: 0,
    }
  },
  created() {
    this.products = productsData;
  }
}

CheckoutView.vue

export default {
  name: "CheckoutView",
  props: {
    cart: Array,
    total: Number
  }
}

I obviously simplified the code to only essentials but to sum everything up: with every request to route "/checkout" i want the cart and total from HomeView to be sent as props to CheckoutView.


Solution

  • You can accomplish this easily with Vue 3. Based on your comments, it seems like you're looking for a straight forward solution without using state management tools like pinia or vuex. Here's what you can do: create a file called cart.js and put it inside a folder named store. Inside that file, handle all the logic related to your global cart state (using ref and reactive), then export it.

    Here is an example, cart.js

    import { reactive } from "vue";
    
    export const cart = reactive([]);
    
    export const addToCart = (item) => {
      cart.push(item);
    };
    

    You can now import this state logics from cart.js to any of your page components.

    Check this demo code