[Vuejs]-How to pass data to another vue.js component

0👍

Please look if somebody already asked a similar question, you can already find two similar questions:

Vue.js, pass data to component on another route

Passing props to Vue.js components instantiated by Vue-router

Anyways, one solution would be to pass your data as a parameter in in router.push method.

Another solution you should consider if you want to use your menuItemsData in other components as well is state management with vuex.

1. Using the router.push params field:

You can either pass menuItemsData as a Parameter via router.push:

router.push({
    path: '/',
    params: {
        menuItemsData: menuItemsData
    }
});

Then you can receive the data in the component you linked to your root url:

export default {
    name: 'timeselect',
    props: ['menuItemsData'],
};

Don’t forget to add the props: true option when you register the timeselect route.

new Router ({
  routes: [
    path: '/',
    component: timeselect,
    props: true
  ]
})

2. Using vuex store for global state management:

For the correct implementation of this concept, vuex has a very good documentation with sample code snippets.

A simple store with your data could look something like this:

// Here we create the state where our data is stored
const state = {
  totalBill: 0.0,
  menuItemsData: {
    Glazed: {
      name: 'Chocolate', 
      qty: 0,
      price: 2.00
    },
    Chocolate: { 
      name: 'Glazed', 
      qty: 0,
      price: 2.00
    }
  }
}

// Here we define the getters to access our data
const getters = {
  getMenuItemsData: state => state.menuItemsData,
  getTotalBill: state => state.totalBill
}

// Here we define mutations which are used for changing our state data
const mutations = {
  addToTotalBill: (state,amount) => state.totalBill += amount
}

// Then we create a new vuex store instance containing our data and the getter, ther you would also add the Mutations for updating the data
const store = new Vuex.Store({
  state,
  getters,
  mutations
})

// Our Vue component which maps our getters to access our data from the vuex store
new Vue({
    store,
    el: '#container',
    computed: Vuex.mapGetters(['getMenuItemsData', 'getTotalBill']),
    methods: Vuex.mapMutations(['addToTotalBill'])
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="container">
  <ul>
    <!-- Now we can just access our data from the store in the component -->
    <h3> Menu Items from store: </h3>
    <li v-for="item in getMenuItemsData">
      <span>{{ item.name }} - </span>
      <span @click="addToTotalBill(item.price)" style="text-decoration: underline; cursor: pointer;">add to Bill</span>
    </li>
    
    <br>
    <span>Total Bill:</span>
    {{ getTotalBill }}
  </ul>
</div>

Leave a comment