Accessing the Vue instance in the beforeEnter hook to utilize its functions

I am facing an issue with accessing the 'Vue' in a beforeEnter function.

Whenever a session expires, a small toast message appears prompting the user to log in again.

The toast message contains a button that, when clicked, should trigger another modal allowing the user to log in. This modal is a separate component within 'Vue'.

How can I access the 'Vue' ('this') to trigger the modal?

I have tried using this.app and this.a.app, along with other suggestions from sources like StackOverflow, but none of them have worked.

Thank you.

Route


{
	path: "/dashboard",
	name: "dashboard",
	component: Dashboard,
	beforeEnter: protectedPage,
	meta: {
		title: "Dashboard"
	}
},

Function


function protectedPage(to, from, next) {
	if (VueJwtDecode.decode(localStorage.token).exp < Math.floor(Date.now() / 1000)) {
		localStorage.removeItem("token");
		Vue.toasted.show("The session has ended. Please login.", {
			theme: "toasted-primary",
			position: "top-center",
			duration: null,
			action: {
				text: "Login",
				onClick: (e, toastObject) => {
					// CODE HERE TO TRIGGER LOGIN MODAL
					next("/");
					toastObject.goAway(0);
				}
			}
		});
		Vue.toasted.hide();
		next("/");
	}
}

Answer №1

While it may not be possible to use a beforeEnter function for this purpose according to the documentation, you can still achieve the desired outcome by utilizing a beforeRouteEnter function within the component itself. This can be done by passing a callback.

beforeRouteEnter (to, from, next) {
    fetchData(to.params.id, (error, data) => {
      next(vm => vm.setData(error, data))
    })
  },

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

Verify that the password is entered correctly in Angular2

My Angular2 form looks like this: this.registerForm = formBuilder.group({ 'name': ['', Validators.required], 'email': ['', Validators.compose([Validators.pattern("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+&bso ...

The value of a variable decreases upon being utilized in an Ajax API call

My tempid variable seems to lose some of its values when passed into the second API call. Despite logging the variable to console (console.log(tempid)) where it appears fine, once placed in the API call it only retains some of its value. I'm uncertain ...

Vue fails to recognize scroll events

Recently, I encountered an issue while trying to utilize the aos library in my Vue application. It appears that the library does not detect the scroll event properly, as it only displays elements on the screen and fails to show others upon scrolling. In a ...

Two distinct iterations of the identical jquery version sourced from external sources

NOTE: This situation involves having two copies of jQuery with the same version number but different libraries loaded by external sources. This is distinct from the issue of using multiple versions of jQuery on a single page, as discussed here: Can I use m ...

Should the request be sent to the parent or child component?

When a page is divided into various components, the data for each component is fetched asynchronously. Therefore, the parent component should trigger the request and pass it on to the child component, or alternatively, the request can be directly sent to ...

Unable to retrieve function variables stored in fancytree source nodes within its activate method

If the configuration of my fancytree includes a source like this: source: [{ title: "Item1", key: "1", myFunc: function (item) { return 'function'; ...

The functionality of "Body Onload" for sending "ScrollHeight" is malfunctioning in Chrome and Safari

I came across an issue where the iframe_resize function in my code was not working as expected. After investigating further, I realized that the problem did not lie with the function itself. So, I decided to post a new question. Within my index.html file ...

What could be causing html-webpack-inline-source-plugin to prevent the page from refreshing after editing CSS files?

Currently, I am utilizing a plugin that embeds all CSS within the final HTML file. This method prevents the application from refreshing in development mode. Whenever I make edits to the CSS, the build process completes normally, but the styles do not updat ...

Let's design a doughnut-style arc chart using the Chart.js plugins

My goal is to design a chart similar to the ones shown in the links below. https://i.sstatic.net/pcyIj.png https://i.sstatic.net/6ZaIZ.png Currently, I have successfully achieved displaying the value in the center using a doughnut chart, but I am strugg ...

Issues arising with VueJS array props when integrating Bootstrap

I am attempting to display two divs next to each other while iterating through props (which are essentially an array) in VueJS. When I have just a single element, everything functions properly. However, as soon as I include the v-for directive, the element ...

What could be the reason for event.stopPropagation() not functioning properly with a switch statement

Could you please explain why the function event.stopPropagation() is not working on the switch element? Whenever I click on the switch, it prints the console log for the switch. However, when I click on the surrounding area (row), it logs the row event in ...

Obtain asynchronous view model for component

Is it possible to retrieve a view model from the server and incorporate it into my component? I attempted to do so with the following code snippet, but it is not working as expected: function fetchViewModelFromServerAsync(){ setTimeout(function(){ ...

"Troubleshooting: Ajax error 'Uncaught ReferenceError: data is not defined' on the

Upon checking the Chrome console, the error message displayed is : Uncaught ReferenceError: data is not defined function list(){ $.ajax({ type:'POST', url:'adeneme.php', data:$('#form1').seri ...

What is the best way to choose the final index value in a drop-down menu?

Is there a way to read and select the last index value in a drop-down using JavaScript? Here is an example of the HTML code: <select name="unqiue"> <option value="number:1" label="1">1</option> <option value="number:2" label="2" ...

The Intersection Observer encountered an issue as it was unable to access the property 'current' since it was undefined

My current project involves the implementation of IntersectionObserver, but I am facing an issue where I receive the error message Cannot read property 'current' of undefined. Can anyone help me identify what might be causing this problem? useOn ...

Is there a way to automatically input an array of elements into a form without having to do it manually

Is it possible to create a form using an array of items fetched from a database, and automatically populate the form with each of these elements? Currently, I'm facing difficulties as the form appears empty. What am I missing? Below is the code I ha ...

Describing a function in Typescript that takes an array of functions as input, and outputs an array containing the return types of each function

Can the code snippet below be accurately typed? function determineElementTypes(...array: Array<(() => string) | (() => number) | (() => {prop: string}) | (() => number[])>) { /// .. do something /// .. and then return an array ...

How to manage form submissions in Vue.js using inputs within child components

I'm working on a parent component that acts as a form. This form consists of multiple child components, each containing input fields. <template> <div class="form"> <generalData v-model="input" /> <textAreas v- ...

AJAX's PUT method encountering issues in Google Chrome

I have successfully implemented this in Mozilla and IE, but for some unknown reason, it is not working on Chrome. In Chrome, the error callback is triggered every time with an error code of zero. Numerous posts on Stackoverflow keep mentioning how all majo ...

Potential Problem Encountered in Verifying Passwords with `bcryptjs` in Node.js and React

Encountering a problem with the bcryptjs library when managing passwords in my application. Registering users works smoothly, but logging in using the same password is causing errors. Despite double-checking the accuracy of the password, it still fails to ...