When preparing to render a page for a specific route, my goal is to fetch the necessary data synchronously first. Ideally, I prefer to handle the data fetching within the page component, but I am open to doing it in the router files as well. I have experimented with different methods, but the challenge lies in the various ways components can be built and the differences in feature usage.
In my scenario, I am creating single file components using the Composition API and <script setup>
syntax. The Vue Router documentation discusses "fetching before navigation" where options like beforeRouteEnter
or beforeRouteUpdate
are mentioned, but these are demonstrated using the Options API. Although there is a section for the Composition API which talks about utilizing onBeforeRouteUpdate
within the setup()
function, experimentation has led me to try out using <script setup>
:
<script setup>
import { onBeforeRouteUpdate } from 'vue-router'
onBeforeRouteUpdate(() => {
console.log('onBeforeRouteUpdate')
})
</script>
Unfortunately, this approach does not work as expected. A method that has shown some success is fetching the data in the router using the beforeEnter
guard and then setting the data onto the meta
property, which can be accessed on the route instance in the component:
beforeEnter: (to, from, next) => {
fetch('https://pokeapi.co/api/v2/pokemon/ditto')
.then(res => res.json())
.then(res => {
to.meta.pokemon = res;
next();
});
}
It's worth noting, however, that as indicated in the documentation, beforeEnter
only triggers when entering the route. Changes in parameters will not trigger this again, requiring the setup of a watcher on the route in the component itself. At this point, it may have been simpler to include all this logic within the component directly.
Despite my efforts, I still haven't found an ideal solution for this process, but I'm open to suggestions and guidance. Any pointers or advice would be greatly appreciated. Thank you in advance.