router.beforeEach in Vue may be executed twice due to: 1. Wrong navigation order; 2. Multiple routing guards; 3. Vuex storage changes. To avoid this, avoid performing navigation in beforeEach, merge multiple route guards, and use watches to listen for Vuex storage changes.
Why does router.beforeEach
in Vue go twice?
router.beforeEach
is a hook function in Vue Router that will be triggered before route navigation occurs. Normally it will only be triggered once, but in some specific cases it may be triggered twice.
Possible reasons:
beforeEach
hook function route navigation, the hook function will be triggered again. This is because route navigation is an asynchronous process, and the beforeEach
hook function may have been executed before it completes. beforeEach
hook function, they will all be triggered. This can lead to duplicate logic or unexpected behavior. beforeEach
hook function relies on Vuex stored state, and a state change is triggered during navigation, the hook function may be called again trigger. This is because Vuex storage changes trigger component re-rendering, which in turn causes route navigation. How to avoid:
To avoid router.beforeEach
triggering twice, you can take the following measures:
beforeEach
hook function: If you need to perform route navigation in the beforeEach
hook function, please use next()
Callback to delay navigation until the current navigation is completed. beforeEach
hook function, please consider merging them into one function. beforeEach
hook function depends on the state of Vuex storage, please use Vuex's watch()
function to listen for state changes instead of triggering state changes during navigation. Conclusion:
router.beforeEach
Triggering twice in Vue is usually due to wrong navigation order, multiple route guards Or Vuex stores changes. By following the measures above, you can avoid this situation and ensure that the beforeEach
hook function executes as expected.
The above is the detailed content of Why does router.beforeEach in vue go twice?. For more information, please follow other related articles on the PHP Chinese website!