Using Vue JS to pass props through the router

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.

  1. How can I pass selectedDishes to the dishes component through the router? Is this the correct approach? (I found a useful article that talks about extracting :dish in routes like /dishes/:dish)

  2. I want to restrict access to selectedDishes to only the parent component. If the quantity of a dish is changed in the dish or checkout 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>

Answer №1

To start building a store for dishes, you can use the following code snippet:

 const store = new Vuex.Store({
  state: {
    dishes: [
      {
        name: '',
        quanity: ''
      }
    ]
  },
  getters: {
    getAllDishes: state => state.dishes,
    getDishByName: (state) => (name) => {
         return state.dishes.find(dish => dish.name === name)
    }
  },
  mutatations: {
  },

})

If you have the dish name available as a path variable from Vue Router, you can query the store to retrieve full details.

For further insights, you may refer to the following resources:

Vuex documentation

Getting started with Vuex

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to duplicate v-models using :value instead of :value?

When using @input and v-model, or @input and :value, I have noticed different behavior. What is v-model doing differently with :value that I am not able to achieve by only using :value? To demonstrate this difference, I have created an example on jsFiddl ...

Toggle the display of dropdown 2 or dropdown 3 depending on the option chosen in dropdown 1

I am struggling with a form that contains 3 dropdowns: <select id="1" required> <option value="">Choose an option</option> <option value="1">Apple</option> <option value="2">Orange ...

Guide to converting JSON data into object structures

Question - How do I convert JSON data into objects? You can find the JSON data here Details - After successfully connecting to the API and retrieving the JSON data, I am looking to map two arrays data.hourly.time[] and data.hourly.temperature_2m[] into a ...

Passing an array of items as a property to a child component in React with Typescript is not possible

In my project, I have multiple classes designed with create-react-app. I am trying to send an array of objects to child components as illustrated below. Items.tsx import * as React from 'react'; import ItemTable from './ItemTable'; imp ...

The $dbServiceProvider in AngularJS, Sqlite, Electron seems to be unrecognized

I am currently working on an electron app that is supposed to display and retrieve items from a SQL database I created. However, I keep encountering an unknown provider error. Despite trying various solutions found online, the issue persists and I am unab ...

Does the Loopback Model have an "exists" method that includes a where clause?

I am interested in querying the data using filters to check for existence. Does loopback support this method of querying? If so, could you provide some guidance? myModel.exists({where: {and: [{city: "London"}, {gender: "F"}]}}, function(err, bool){ if(bo ...

Can the optionsText be shown while saving the optionsValue in a dropdown menu?

Here is the code snippet I am currently working with: var model = function() { this.nameSomething = ko.observable(''); this.nameId = ko.observable(0); }; var vm = (function() { var myList = [{ id: 1, type: 'foo1'}, { id: 2, ...

Tips for organizing the output of items from the .getJSON method

I am currently facing an issue where my output is displayed on the page in the same order as the raw JSON file. I am seeking assistance on how to sort the items based on a specific property within each item. For instance, I would like to sort alphabetical ...

Error 422 encountered while trying to create a new asset using the Contentful Content Management API

My attempt to create and publish an image as an asset using the Contentful Content Management API has hit a roadblock. I managed to successfully create and publish an entry, but I can't seem to figure out why creating an asset is not working as expect ...

VueJS dynamic AppBar based on certain conditions

When using Vuetify, what is the most efficient method for managing differently styled appbars on different pages? Additionally, how can the back button be activated instead of the hamburger icon through programming? For instance, if there are 5 screens a ...

What is the best method for retrieving the selected itemsPerPage in Vuetify's data-table in version 2.0

Recently, I've been struggling to retrieve the selected items-per-page on a Vuetify data-table due to some recent changes. I came across this helpful example: How to set initial 'rows per page' value in Vuetify DataTable component? Here is th ...

The onProgress event of the XMLHttpRequest is triggered exclusively upon completion of the file upload

I have a situation with my AJAX code where the file upload progress is not being accurately tracked. The file uploads correctly to the server (node express), but the onProgress event is only triggered at the end of the upload when all bytes are downloaded, ...

Creating route in Node.js using the forEach method

While attempting to create routes for each ID using a forEach loop, I encountered a problem where the second route would not run and the application would continue loading until a timeout is reached. I have checked all the expected values and everything se ...

Retrieve the elements with the largest attributes using the find method exclusively

UPDATE: After some trial and error, it seems like using the find method won't work for this particular scenario. I managed to come up with a workaround by introducing a boolean field called "last_inserted" and utilizing Meteor hooks to ensure that onl ...

Steps to resolve the Angular observable error

I am trying to remove the currently logged-in user using a filter method, but I encountered an error: Type 'Subscription' is missing the following properties from type 'Observable[]>': _isScalar, source, operator, lift, and 6 more ...

Tips for determining the zoom factor through mouse scrolling using jQuery

Is there a way to zoom in on a page when the user scrolls using ctrl + ,? If I determine the Zoom factor, can I then zoom in on the current page based on that factor? For example, if the zoom factor is 1.44, can I convert this to 144% and carry out the ...

Retrieve the text input from the text field and display it as

Is there a way to display what users enter in a textfield when their accounts are not "Activated"? Here's an example: if(active == NULL);{ //I've attempted the following methods. //In this scenario, 'username' is the name of ...

Reorganize external dependencies in the wwwroot directory using gulp

In my development setup using VS 2015, ASP.net vnext, Angular 2, Typescript, and gulp.js, I have successfully automated the process of moving my scripts/**/*.ts files to the wwwroot/app folder. Now, I am looking to extend this automation to include my libr ...

Choosing a specific element within another element of the same type using JQuery

I've created a complex nested HTML structure shown below: <ul class="root"> <li>Foo 1 <label class="bar-class">bar</label> <ul> <li>Foo 2 <label class="bar-class">bar</label> ...

Adding a badge to a div in Angular 6: What you need to know!

How can I add a badge to a specific div in Angular 6? I have dynamic div elements in my HTML. I want to increase the counter for a specific div only, rather than increasing it for all divs at once. For example, I have five divs with IDs div1, div2, div3, ...