#title Weekly Vue News #81 - Re-Rendering Vue Routes When Path Parameters Change #preview Ready for your weekly Vue & Nuxt dose?
Re-Rendering Vue Routes When Path Parameters Change
Hi π
I had to switch from
The paid plan for Cloudinary would be 99β¬/month π€― Therefore, I moved all images to an AWS S3 bucket and let them process them via
I'm busy producing Vue & Nuxt tips for upcoming newsletter issues.
Unfortunately, I also have a full backlog of blog post articles I would like to write...
Too many ideas, too little time π₯
Have a lovely week βοΈ
To support me:
- π Recommend the newsletter to your friends: it really helps!
- πΈ Sponsor the newsletter
- π§΅ Retweet the latest Twitter thread
- π¨ Reply to this email: feedback is welcome
In Vue applications, we use
A typical use case is a dynamic route pattern with params: /users/:id
. It allows you to specify a parameter in the URL. The :id
in this route pattern is a placeholder for a dynamic value, which can change based on the user's actions. Typically you will trigger a backend endpoint with the given id
to fetch user details.
Let's take a look at an example:
The demo code of this article is interactively available in the following StackBlitz project:
1 <script setup>
2 import { ref, onMounted } from 'vue'
3 import { useRoute, useRouter } from 'vue-router'
4 import UserId from '@/components/UserId.vue'
5 import { getUserDetails } from '../api/userApi.js'
6
7 const route = useRoute()
8 const router = useRouter()
9
10 const loading = ref(false)
11 const details = ref(null)
12
13 async function fetchDetails(id) {
14 loading.value = true
15 try {
16 details.value = await getUserDetails(id)
17 } catch (error) {
18 console.error('Failed to fetch details', error)
19 details.value = 'Error'
20 } finally {
21 loading.value = false
22 }
23 }
24
25 function navigateToNextUser() {
26 const nextId = Number(route.params.id) + 1
27 router.push({ name: 'UserDetails', params: { id: nextId } })
28 }
29
30 onMounted(async () => {
31 console.log('UserDetails mounted')
32 fetchDetails(route.params.id)
33 })
34 </script>
35
36 <template>
37 <h2>User Details</h2>
38 <div>
39 <span>ID: {{ route.params.id }}</span>
40 <span v-if="loading">Loading details ...</span>
41 <span v-else>Details: {{ details }}</span>
42 <button @click="navigateToNextUser">Next User</button>
43 </div>
44 </template>
This component uses the onMounted
lifecycle hook to fetch user details when the component is mounted. The user's ID is read via route.params.id
from the useRoute
composable.
So far, everything works fine and the user details are visible and they get updated if we update the route path manually by changing /users/1
to /users/2
.
But our component contains a button that triggers a programmatic route update using router.push
.
Programmatically altering the path does not trigger the re-rendering of the view. As a result, the mounted()
hooks do not fire, and the nested components do not reload, leading to unexpected behavior.
Solution 1: Watcher
The simplest solution is to add a
1 <script setup>
2 // ...
3
4 watch(
5 () => route.params.id,
6 (newId, oldId) => {
7 fetchDetails(route.params.id)
8 }
9 )
10 </script>
Solution 2: Route Guard
Another solution is the
1 <script setup>
2 // ...
3
4 onBeforeRouteUpdate(async (to, from) => {
5 if (to.params.id !== from.params.id) {
6 fetchDetails(route.params.id)
7 }
8 })
9 </script>
Of course, you can also use the
It adds a navigation guard that triggers whenever the current location is about to be updated. Similar to beforeRouteUpdate
but can be used in any component. The guard is removed when the component is unmounted.
Difference Between Solution 1 & 2
There is a big difference between using watch
and beforeRouteUpdate
:
The route guard is called before the value of the route
object actually changes. The watcher is called after the value of route
has changed.
Using the beforeRouteUpdate
navigation guard, you can determine whether or not you want to prevent the route from changing or go to a different route entirely.
ππ» Volar, previously the official Vue VSCode extension, is now an embedded language tooling framework. |
ππ» It can process any file format that involves embedded languages. |
ππ» In this article, you'll learn how to create a reporting app with Vue 3 and Composition API. |
ππ» Flexmonster Pivot Table & Charts and Highcharts libraries are used. |
ππ» In this article, Fotis investigates different options to create transitions and micro-interactions.
fadamakis.comππ» Evan You tells us what to expect in 2023 from Vue.js. |
ππ» He is the creator of the JavaScript framework Vue.js and the frontend build tool Vite. |
ππ» Responsive scrollable videos without obscure video encoding requirements. |
ππ» Compatible with React, Svelte, Vue, or just plain HTML. |
ππ» Adds enhanced support when inspecting Vue source
developer.chrome.comππ» Chrome tracing lets you record a performance trace that captures low-level details of what the browser is doing. |
ππ» This post is a short guide on how to use this tool, from a web developerβs point of view. |
ππ» Veracodeβs State of Software Security report for 2023 found that JavaScript Applications Have Fewer Security Flaws Than Java and .NET Applications.
www.infoq.comππ» A compiled-away, type-safe, readable RegExp alternative. |
ππ» |
ππ» Nix is a tool that builds packages in isolation from each other to ensure that they are reproducible and don't have undeclared dependencies.
zero-to-nix.comUntil next week,
Holzapfelkreuther Str. 19, 81375 Munich, Germany