Unlocking the data within an object across all Components in Vue

Recently, I've started using Vue and encountered a problem. I'm trying to access data stored inside an Object within one of my components. To practice, I decided to create a cart system with hardcoded data for a few games in the app. Below is the code snippet for the Object:

products: [
                { 
                    id: 1, 
                    name: 'Call of Duty: Modern Warfare',
                    price: 'Rs. 5,500',
                    shortDesc: 'Call of Duty: MW returns. This game is a complete revamp of the old COD:MW',
                    description: 'Call of Duty: MW returns. This game is a complete revamp of the old COD:MW',
                    inStock: 'yes',
                    availableQuantity: '100',
                    img: 'src/assets/img/codmw.jpg',
                },
                { 
                    id: 2, 
                    name: 'PlayerUnknowns Battlegrounds',
                    price: 'Rs. 600',
                    shortDesc: 'Call of Duty: MW returns. This game is a complete revamp of the old COD:MW',
                    description: 'Call of Duty: MW returns. This game is a complete revamp of the old COD:MW',
                    inStock: 'yes',
                    availableQuantity: '500',
                    img: 'src/assets/img/pubg.jpg',
                },
                { 
                    id: 3, 
                    name: 'GTA VI',
                    price: 'Rs. 10,000',
                    shortDesc: 'Call of Duty: MW returns. This game is a complete revamp of the old COD:MW',
                    description: 'Call of Duty: MW returns. This game is a complete revamp of the old COD:MW',
                    inStock: 'yes',
                    availableQuantity: '5',
                    img: 'src/assets/img/gta.jpg',
                }
            ]

The above data is located in the Shop.vue component. Whenever a user clicks on the "View Product" button, a separate route for that specific product is called. Now, I need to fetch the data of that particular game in the ViewProduct.vue component. For this purpose, I added a button in Shop.vue like the one below:

<router-link 
    class="btn btn-primary" 
    :to="/view/ + game.id" 
    v-b-tooltip.hover title="View Product details">
    View Product
</router-link>

This button opens up a new route with the path "view/ID", where ID is dynamic. In the view route, I access this dynamic ID using:

this.$route.params.id

Now, my challenge is how to access the data of the product with an ID that matches the dynamic ID mentioned above in the ViewProduct.vue component since the Product Object is in the Shop.vue component?

If you have any suggestions or solutions, please help me out. Thank you!

Answer №1

Vuex is a solution to this issue. Passing props between components can be achieved in the following manner:

const router = new VueRouter({
  routes: [
    { path: '/view/ + game.id', component: ViewProduct.vue, props: { id:this.id } }
  ]
})

Inside the ViewProduct component:

export default {
        data() {
            return {

                },
            };
        },
        props: ['id'],     <===== *props*
        computed: {

        },
        methods: {
        },

The props can then be accessed from within the ViewProduct component using:

this.$props.id

Answer №2

To efficiently manage the state in your application, utilizing a global state is highly recommended.

One popular option to achieve this is by incorporating Vuex into your project.

You can designate your list of items as the state and implement a getter using method style access to retrieve specific items based on their unique identifier.

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

Is it possible to utilize TypeScript code to dynamically update the JSON filter with variable values?

I am dealing with a JSON filter in which the value for firmwareversion needs to be replaced with a dynamic value. Here's how I've set it up: //JSON filter this.comX200FilterValue = '{ "deviceType": "ComX", "firmwareV ...

Exploring the bounds of self-invocation functions in JavaScript

Have you ever wondered why self-invocation functions inside another function in JavaScript don't inherit the scope of the outer function? var prop = "global"; var hash = { prop: "hash prop", foo: function(){ console.log(this.prop); ...

Redux actions do not cooperate with functions, preferring to be implemented inline instead

I am a beginner in Redux and JavaScript and just came across this issue, When I use the line dispatch({type: 'REQUEST_START'}); it works fine, but when I write it like this: dispatch(requestStart); No actions are being fired! Any suggestions ...

Adjusting the input in a Textfield within React using Material UI

const [formData, setFormData] = useState({}); useEffect(() => { fetch("/formdata") .then((res) => res.json()) .then((data) => setFormData(data)); }, []); console.log("Form Data", formData); //Sorting by order let attr; ...

Issue encountered while subscribing to SalesForce topic using Node.js

Attempting to subscribe to a SalesForce topic through a Node.js server using the code provided in the JSForce documentation: conn.streaming.topic("InvoiceStatementUpdates").subscribe(function(message) { console.log('Event Type : ' + message.ev ...

Monitoring browser closure and page transitions in VueJs

I am attempting to detect when a user changes or inserts input in a form and then tries to navigate away from the page, in order to provide them with a warning. I have searched for solutions but have not yet found one that works for me. <b-form-group ...

Unable to alter the state through the URL bar using ui-router

I am facing an issue where I get redirected to the home state whenever I try to directly access a URL like mysite.com/#!/about. My menu with ui-sref links is functioning correctly, but when it comes to nested states, I encounter problems switching betwee ...

What advantages does leveraging GraphQL with React offer compared to using GraphQL with Vue, Ember, or Angular?

Curious if there are any advantages to combining GraphQL, created by Facebook, with React? Or is it better to use a different JavaScript framework like Vue, Angular, or Ember instead? ...

Unable to access the suggestion list within the modal

I incorporate the PrimeNG AutoComplete feature within a PrimeNG Dialog, displaying a list of elements below the AutoComplete in the dialog. My objectives are: To set the max-height of the modal dialog to 300, and have a visible scrollbar if the total ...

Is there a way for me to retrieve the pageProbs that I have shared with a Component in _app.js?

Upon the loading of my website, I am fetching a large amount of data using getInitialProps. MyApp.getInitialProps = async (appContext) => { // Calls page's `getInitialProps` and fills `appProps.pageProps` const appProps = await App.getInitialProps( ...

JavaScript: utilizing JSON, implementing dynamic methods for creatures, and utilizing closures for encaps

Apologies for the unclear title, but I am unsure where the issue lies. Therefore, my task is to create a function that generates JavaScript objects from JSON and for fields that start with an underscore, it should create setters and getters. Here is an e ...

Tips for showing information following a click on a cell populated by a v-for loop in a table

In my component, there is a list of 'matches' displayed. When a user clicks on a particular cell, it should show detailed information about that match using a child function called passData(value). The data is shown in a table using v-for: ... & ...

We have successfully implemented version x3 validation using Netlify forms

Currently, I have a functional form that submits using Netlify forms, making the process straightforward by simply adding name="contact" data-netlify="true" method="POST". This setup handles all the backend work seamlessly. The basic structure of my form ...

Sending various values via a click in an HTML link

Hello, I am attempting to pass multiple values using the HTML onclick function. I am utilizing Javascript to generate a table dynamically. var user = element.UserName; var valuationId = element.ValuationId; $('#ValuationAssignedTable').append(&a ...

vee-validate's implementation of useFieldArray is specifically designed to function exclusively with object deconstruction

Greetings everyone, Could someone please shed some light on why vee-validates useFieldArray only functions correctly when I destructure it? Here is the template: // In the functioning example, I utilize "fields" instead of fieldArray.fields. ...

React Modals: Only the modal component triggered by the first click will open, with no other modals opening

As a newcomer to StackOverflow, I apologize if my problem description is not clear. I am currently learning React and working on a course-search app as a project. The app filters courses based on user input from a JSON file and displays them in cards with ...

Tips on creating a hierarchical ul list from a one-dimensional array of objects

I have an array filled with various objects: const data = [ {id: "0"},{id: "1"},{id: "2"},{id: "00"},{id: "01"},{id: "02"},{id: "11"},{id: "20"},{id: "23"},{id: & ...

Angular Validation displays ng-valid when the form is actually invalid

I am currently working on a wedding RSVP form https://i.stack.imgur.com/Ct8Ux.png My objective is to hide the DONE submit button and only display it when the form is considered valid. <form method="POST" action="http://l.bheng.com:8888/wedding" acce ...

Exploring Fetch API with Promise.all

I have successfully implemented a functionality that fetches data from two URLs and performs an action only when both requests are successful. However, I am curious if there is a more efficient and succinct way to achieve the same result. Helper functions ...

Choosing a single radio button value within a nested ng-repeat loop in AngularJS

Help needed with selecting only one radio button value in nested ng-repeat. Please review the source code and suggest any potential mistakes. <form ng-submit="save()"> <div ng-repeat="x in surveyLst"> <div class="row"> < ...