2

I have an issue where I need to call a function every time the user reloads the page. Normally this would work by just using the created hook on App.vue, but since this project autogenerates the base component I'm not able to do this here.

I don't want to call this function when the user is navigating between routes, only when the page is reloaded/refreshed.

amani2k
  • 77
  • 4
  • 1
    The project autogenerates the component? What does it mean? Also, if you want to have it, you call it on `mounted()` on your default layout. What will be loaded exactly? – kissu Nov 12 '21 at 21:46

2 Answers2

2

I think that you do have not many options here, as far as I can see, because we can know that the page has been refreshed only from the browser, which means that you need to find a cross-browser solution.

Vue way: But you could keep this component alive and execute your code in created hook, and the code that should be executed when route changes is executed in route change hooks (beforeRouteEnter, etc.).

JS way: I suppose to think that PerformanceNavigationTiming API is the right what you need. Here you can find a detailed description of this method.

P.S. - Pay attention to browser support and that a lot of people use Apple devices.

peperoneen
  • 141
  • 5
  • The Vue solution will not work. The other may maybe work, good one! – kissu Nov 12 '21 at 22:02
  • @kissu Why not? – peperoneen Nov 12 '21 at 22:11
  • Having a `keep-alive` in your whole app to trigger some functions in the same way of a middleware is really not what OP asked here. And it's not a good way of doing things neither. – kissu Nov 13 '21 at 22:41
  • 1
    @kissu Yes, actually it's (Vue way) not the good way, but it's still possible because I went to say that we can check if that was a routing or not in `beforeRouteEnter` hook (because we have `from` argument), for example, and do what we need to in there. Your solution is exactly what I went to say but has been made correctly, happy to upvote you. P.S. - `keep-alive` is not an option in this case. I didn't notice that we are talking about a core component. – peperoneen Nov 14 '21 at 06:17
2

You can call it in a beforeMount() in the default layout.

kissu
  • 40,416
  • 14
  • 65
  • 133