If I include beforeRouteEnter in one component, the this.$route property may become undefined in another component

I seem to be encountering an issue. After implementing a beforeRouteEnter method in one component, I am unable to access this.$route in another component.

Here is the structure of my app:

<div id="app">
    <settings-modal></settings-modal>

    <router-view name="CalendarMonthView"></router-view>
</div>

The CalendarMonthView component is rendered in the router view and contains a beforeRouteEnter method. However, once this method is added, the SettingsModal component reports that this.$params is undefined during its created() lifecycle hook. This was not the case before implementing beforeRouteEnter.

CalendarMonthView component

export default {
    ...

    // to.params.selectedYear  = 2019
    // to.params.selectedMonth = 3

    beforeRouteEnter (to, from, next)
    {
        Month.getDays({
            year: to.params.selectedYear,
            month: to.params.selectedMonth,
         }).then(response => {
             store.monthDays = response.data
             next()
         })
    }
}

SettingsModal component

export default {
    ...

    created()
    {
        // undefined
        console.log('selectedYear: ', this.$route.params.selectedYear)

        // undefined
        console.log('selectedMonth: ', this.$route.params.selectedMonth)
    }
}

Answer №1

It seems like you're referencing the Month.getDays() function, but I'm not familiar with it. It's possible there was a mistake in the code that prevented the next() function from being triggered. I recommend verifying the accuracy of your function to ensure everything is working properly.

Answer №2

The route parameters are not yet accessible because the navigation process has not been completed. It is necessary to wait for the promise returned by Month.getDays to be resolved.

Attempting to retrieve the parameters from SettingsModal immediately upon creation, before the promise is resolved, will result in an error.

One approach is to use a watch on $route to monitor and access the params once they are available.

watch: {
  '$route': 'checkParams'
 },

This code should be added to SettingsModal.

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

Tips for sending a JavaScript variable through an AJAX URL

I currently have a variable defined like this: var myip; I need to include this variable in the following URL: $.ajax('http://api.ipstack.com/**[myip]**?access_key=mykey') Manually replacing [myip] with my IP address works fine, but I am loo ...

What causes the Vue.http configuration for vue-resource to be disregarded?

I am currently utilizing Vue.js 2.3.3, Vue Resource 1.3.3, and Vue Router 2.5.3 in my project while trying to configure Vue-Auth. Unfortunately, I keep encountering a console error message that reads auth.js?b7de:487 Error (@websanova/vue-auth): vue-resour ...

The C# MVC Controller is having difficulty retrieving decimal or double values from an Ajax POST request

Having trouble sending decimal or double values via ajax to my C# MVC Controller. The values always come through as null, even though they work fine when sent as strings or integers. Why is this happening? When checking the client's request, the corre ...

Comparing functions and function issues when using onClick in JavaScript

I have successfully created an Image Element on my web page dynamically using JavaScript. I am now trying to set an onClick event for the newly created image element. However, I am encountering a problem and I cannot figure out why?, This is the code I ...

Load Form with Json Data from LocalStorage Key-ID to Auto-Populate Fields

After successfully setting the ID in localStorage, I now need to retrieve and display only that specific record from my JSON data. The content of my localStorage is: This information is obtained from my JSON data after a button click. The challenge is us ...

"Utilizing jQuery's getJSON method in a session to fetch data

I have a code snippet that fetches the current number of likes on Facebook like this: $(document).ready(function() { $.getJSON('https://graph.facebook.com/<username>?callback=?', function(data) { var fb_count = data['likes ...

transferring information between two html pages using javascript

Although this question has been raised multiple times, I have gone through the answers and attempted various solutions, however, my code is still not functioning correctly. Below are my working files : my_app -index.html -task1 -index.html I ...

Can Sequelize be used to perform queries based on associations?

I have designed a data structure that includes an n:m relationship between "Rooms" and "Users." My current goal is to remove or delete a room. To accomplish this, I need to verify if the user initiating the deletion process is actually present in the room ...

Tips on accessing information from a JSON file

I am facing an issue while trying to extract data from a JSON object that was passed from the servlet. The keys in my JSON object are numbered, and I need to append these numbers to the names of the keys. The structure of my response is as follows: {"sha ...

What is the procedure for updating or adding data to a JSON file with angularJS?

After successfully creating a local JSON file and retrieving data from it using app.controller('appCtrl', function($scope, $http){ $http.get('employees.json').success(function(data){ $scope.employees=angular.fromJson(data.employee ...

Executing an external script in Nuxt after re-rendering: Best practices?

Looking for a solution in Nuxt/Vue to properly execute an external script (hosted by a third party) after the DOM has successfully rerendered on every route. The challenge arises when using a script that dynamically adds elements to the dom, causing confl ...

What is the best way to title an uploaded chunk with HTML5?

Here is the script I am working with: function upload_by_chunks() { var chunk_size = 1048576; // 1MB function slice(start, end) { if (file.slice) { return file.slice(start, end); } else if (file.webkitSlice) { ...

Import a JSON file into Parse by reading and parsing it to store in the database

I am currently facing a challenge with parsing JSON data in my Parse Cloud function. After fetching the JSON file, I need to parse the data and populate one of my classes with the results. However, I'm having trouble figuring out how to properly parse ...

Upon receiving the ajax request, the entire code page is called back

I'm having trouble saving data using a button in Laravel. When I use console.log, the entire code appears in the console and I don't understand why this is happening. Here is my input field and button: <form action="{{ url('sendcom& ...

Conceal specific pages within the DataTable without deleting them

Currently, I am facing an issue where the dataTable paginates and removes the DOM pages along with the data. My goal is to extract all the data from the dataTable and convert it to JSON without losing access to the DOM when pagination occurs. I want to m ...

A collection of collections

Alright, listen up. I've got a JSON file with an array inside another array. Here's a snippet of the JSON file: { "keys": [ { "game": "Counter-Strike: Global Offensive", "price": "5", "listofkeys" ...

Are you searching for the origin of a dynamic dropdown widget or database?

Currently, I am browsing through and I have a query regarding accessing all available classes/options for the courses in a semester. There is a class locator on the top left of the page with a dynamic drop-down menu. Can anyone suggest how I can access ...

Triggering a reload on the vuejs router from an external application

I'm facing a bit of a mess here, as it seems like the usual solutions for forcing a refresh in a Vue app aren't working. I have a basic page that uses some jQuery to load a third-party Vue.js app. The app loads fine and functions well. The issue ...

React does not recognize data.map as a function

Currently, I am facing an issue with a simple map function in React that is supposed to create a set amount of times. {times.map((time) => ( <Pill value={time} handleTimes={handleTimes} key={time} /> ))} The error being thrown i ...

Utilizing v-for and CSS Grid to showcase data effectively

I'm having trouble organizing my Vuex data with CSS GRID. It's turning out messy. My setup includes two columns: the first one for labels and the second for values. {{$store.state.stepOne.textfield[idx].label}} The code above is used to displa ...