My goal is to create an array called selectedDishes
in the parent component that will store dishes selected by the user along with their quantities. I want to be able to use this data in all other components within the router. For example, I have a dish
component, but I also need to access selectedDishes
in the checkout
component and other components.
How can I pass
selectedDishes
to thedishes
component through the router? Is this the correct approach? (I found a useful article that talks about extracting:dish
in routes like/dishes/:dish
)I want to restrict access to
selectedDishes
to only the parent component. If the quantity of a dish is changed in thedish
orcheckout
component, it should be sent back to the parent component and then passed down as a prop to child components. Is this the right way to handle it?
Parent Component:
<template>
<view-router v-on:addQuantity="addQuantity(...arguments)"></view-router>
</template>
<script>
data: () => ({
// How can I pass this data to the dishes component?
selectedDishes: [{name:'Soup', quantity: 10}, {name:'Sushi', quantity: 5}],
}),
methods: function(){
addQuantity: function(dishName){
this.selectedDishes.forEach(function(item, index){
if(item.name == dishName){
this.selectedDishes[index].quantity +=1
}
})
}
}
</script>
Router:
import VueRouter from 'vue-router';
let routes = [
{
path: '/',
component: require ('./components/vmMain'),
children: [
{
path: 'dishes/:dish',
component: require ('./components/Dishes')
}
],
},
]
Dishes Component:
<template>
<div
// If the URL is 'dishes/Soup', I want to display the following information
//<h1>Soup</h1>
//<h2>10</h2>
<h1>dish.name</h1>//currently accessing using this.$route.params.dish
<h2>dish.quantity</h2> //unable to access quantity
<button v-on:click="addQuantity(dish.name)">add</button>
</div>
</template>
<script>
methods: function(){
addQuantity: function(dishName){
this.$emit('addQuantity', dishName)
}
},
// How can I pass a prop from the parent component?
props['dish']
</script>