Vue Routing

up:: Vue ( Nuxt has some built-in functions that make this even more convinient. )

Router configuration

import { createRouter, createWebHistory } from 'vue';
import TeamsList from '...';
 
const router = createRouter({
	history: createWebHistory(),
	routes: [
		{ path: "/teams",  component: TeamsList }
	]
});
const app = createApp(App);
app.use(router)

Dynamic routes

const router = createRouter({
	routes: [
		{ path: "/teams/:teamId", // prefixed with colon
		  component: TeamMembers }
	]
}); 

Get access in the created Vue Instance Lifecycle:

created() {
	// this.$route.path // see the whole path
	// this.$route.params // get the parameters
	this.$route.params.teamId // access a specific parameter
 
	// search for a fitting id
	const selectedTeam = this.teams.find((team) => team.id === teamId)
}

Using props

Gotcha

When navigating from a dynamic route to another dynamic route, the component doesn’t get reloaded. That is because we call the route in created. Vue doesn’t create and destroy the component, it is cached.

const router = createRouter({
	routes: [
		{ path: "/teams/:teamId", // prefixed with colon
		  component: TeamMembers,
		  prop: true }
	]
}); 

This code above is not completed, but it starts something like this.

router-view

Let the template know where to render it:

<main>
	<router-view></router-view>
</main>

Navigate (vue’s replacement of a href essentially):

<router-link to="/teams">Teams</router-link>

Styling

  • router-link-active: Applied to any item that fits part of the url.
  • router-link-exact-active: Applied when the whole url matches the whole path.

(through Vue Methods) (Nuxt does this with Nuxt navigateTo)

methods: {
	navigateToOtherSite() {
		this.$router.push('/teams'); // takes us to '/teams'
		this.$router.back(); // emulates the browser's back button
		this.$router.forward(); // emulates the browser's forward button
	}
}

Redirects

const router = createRouter({
	routes: [
		{ path: "/",  redirect: '/teams' }
	]
}); 

You can also add alias on the other route. What is important to know is that the ** then.

Catch-all routes

const router = createRouter({
	routes: [
		// this one needs to come last, otherwise it overwrites everything else
		{ path: "/:notFound(.*)", component: 'NotFound'}
	]
}); 

You can also add a children parameter to each list. That makes it a sub-path.

Then you need to add an extra router-view in the parent component.

Query parameters

this.$route.query