What is the best way to deliver data from the main Vue instance to components that are being utilized by vue-router?

Currently, I am utilizing vue-router within a single HTML file instead of using separate file components. I am encountering an issue where I am unsure how to pass the data stored in the Vue data object to the component when loading it for a route.

Oddly enough, everything functions as expected when I load the component without Vue-router. However, when I attempt to make the route load the component, it ceases to work properly.

const searchResults = Vue.component('search-results', {
                props: [
                    'results',
                    'page',
                    'totalPages',
                    'resultsContainerHeight'
                ],
                template: 
                <div>
                    <div style="height: 30px;"></div>
                    <div id="results-container" v-bind:style="{ minHeight: resultsContainerHeight + 'px' }">
                        <div class="card border-dark mb-3" v-for="result in results">
                            <div class="card-body text-dark">
                                <span class="float-right">{{Number(result.distance).toFixed(1)}} kms</span>
                                <h5 class="card-title">{{result.name}}</h5>
                                <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                            </div>
                        </div>
                    </div>
                    <nav v-if="totalPages > 1">
                        <ul class="pagination justify-content-center">
                            <li class="page-item" v-bind:class="{disabled: page == 1}">
                                <a class="page-link" href="#" @click="$emit('change-page',page-1)">Previous</a>
                            </li>
                            <li class="page-item" v-bind:class="{active: index+1 == page}" v-for="(pageNo,index) in totalPages"><a class="page-link" @click="$emit('change-page',index+1)" href="#">{{index + 1}}</a></li>
                            <li class="page-item" v-bind:class="{disabled: page == totalPages}">
                                <a class="page-link" href="#" @click="$emit('change-page',page+1)">Next</a>
                            </li>
                        </ul>
                    </nav>
                </div>
            });
        const router = new VueRouter({
            routes: [{
                path: "/",
                component: searchResults,
                props: {
                    results,
                    page,
                    totalPages,
                    resultsContainerHeight
                }
            }

            ]
        });
        var app = new Vue({
            router,
            el: '#app',
            data: {
                results: [],
                latLng: '',
                page: 1,
                totalPages: '',
                resultsContainerHeight: ''
            }

I am currently receiving the error:

Uncaught ReferenceError: results is not defined

My goal is for the route to function in the same manner as it does when I load the component without using the router.

Answer №1

The child component has now become a part of the main instance and can no longer directly access the parent's properties. However, there are multiple strategies to work around this limitation.

For simpler cases, it is sufficient to access the parent using this.$parent or simply $parent in the template.

As applications grow more complex, relying on this approach becomes increasingly difficult to manage, prompting the need to explore tools like 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

I'm wondering if you have any insights on how to retrieve objects using Mono WebAssembly

I am looking to send a c# object back via mono-wasm, but when I attempt to do so, the returned object appears in my JavaScript file here. The C# code can be found in [image2]: C# code My JavaScript code can be found here: JS code Everything seems to wor ...

Iterating through and dispatching to the modal窶ヲ

Can someone help me figure out why I am encountering a problem where clicking on the button below results in seeing three different objects before being told that invoice is undefined? <tr :key="invoice" v-for="(invoice, index) in invoices"> & ...

`Can you explain how to specify the elements of an array within a form using AngularJS?`

Below is an array containing objects: //Data source code $scope.data = [ { name: 'Lname', items: [{ label: 'Lastname', type: 'text', model: 'lname', pattern: '/^[a-zA-Z]$/', ...

Highlight and trim lengthy text using React

Imagine I have a lengthy text: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo con ...

A guide to spinning an image in every direction with CSS

I'm working on rotating an image in all directions using CSS and Vue.js. To demonstrate this, I have created a CodePen with the necessary code below. <div id="app"> <v-app id="inspire"> <div class="text-xs-center image-rotation" ...

The logo marquee unexpectedly bounces up and down at the end of every

Struggling with a JavaScript code issue. The Logo marquee suddenly jumps at the end of each loop: I've tried everything, but I can't seem to fix it and make it work as intended Here's the complete script that technically works, but causes ...

Node: Sending JSON Values in a POST Request

I am currently working with the index.js file below: var Lob = require('lob')('test_6afa806011ecd05b39535093f7e57757695'); var residence = require('./addresses.json'); console.log(residence.residence.length); for (i = 0; i ...

Exploring navigation within a React application

After attempting to develop a react native application and finding it too difficult for my needs, I decided to switch to React. As a beginner in web programming, I recall learning about the concept of 'navigation' in react native, including vario ...

Issue with dialogue not appearing when clicking on a table cell

UPDATE: I am facing a challenge with this code not displaying a dialog upon click.: The issue lies in the fact that nothing happens when the Title is clicked. Any suggestions? The data is present, as removing the .hidden CSS class reveals it. $(". ...

Why is the deployed Express server failing to establish a session?

After deploying a node express server on Digital Ocean, I encountered an issue where the session was not being created. To address this, I implemented a store to prevent memory leak and included app.set('trust proxy', 1) before initializing the s ...

Removing the new line using v-if in Vue.js

I want to insert a v-if in the middle of a sentence without creating a new line. This is what I desire: A / B / C / D However, my current output is: A / B / C / D This is the code I am using: <div> {{ A }} / {{ B }} <p v-if="functi ...

Looping through multiple lines of output in VueJS

Looking for a solution to optimize my for loop <div class="w3-panel w3-blue w3-card-4" v-for="peer in peers" v-bind:key="peer" > {{ peer.hop }} {{ peer.time }} </div> ...

Switch out the vuetify simple-table for the data-table component

I need help transitioning a basic table in Vuetify with no headers and one column to a v-data-table. How can I make this change? <v-simple-table> <thead /> <tbody> <tr v-for="item in categories" ...

"Utilizing Dynamic Dropdown Options Pulled from Database and Automatically Refreshing List upon

I am facing a dilemma with displaying dropdown menus for Provinces and Cities, both of which have values coming from the database. While I can easily list the values for Provinces by querying all of them, my issue arises when it comes to displaying Cities. ...

When processing a response from the backend (using express js), cookies are not being received in the browser while on localhost

I'm currently facing some difficulties with implementing authorization cookies within my application. Whenever I attempt to send a GET request to my API (which is hosted on port 8080) from my React frontend (running on port 3000), the cookies that I ...

What is the best way to manage a promise's response?

I'm currently facing a situation where I need to create a petition to an endpoint and retrieve the URL of the backend that I intend to use. My setup involves a file with the API configuration where I instantiate axios. Previously, my approach was sim ...

What is the best way to retrieve an element made in a different function within JavaScript?

I have a main button on the screen and when I click that button, it generates two more buttons. These additional buttons should each have their own functionality and click events, but since they are created within a function without global variables or ids ...

What is the best way to enforce constraints on three keys when validating an object using Joi?

Currently experimenting with Joi for object validation. Able to validate objects with constraints on two keys using any.when(). Now looking to implement validation with constraints on three keys, for example: var object = { dynamicPrize: false, ...

Troubleshooting: How to Fix Missing Sum Display in HTML Input Fields

I am new to the world of website programming and I am currently working on creating a basic sum equation using two input fields from the client-side. <!DOCTYPE html> <html> <head> </head> ...

Utilize a single JWT token across various Vue.js applications

Can JWT tokens be shared between several Vue.js applications that are hosted on the same domain? For instance, having a primary app for user login and transactions, and a reviews app in a subdirectory where users can only leave reviews. ...