SoFunction
Updated on 2025-04-04

Vue 3 uses vue-router to navigate and listen for routing changes

1. Use useRouter for navigation

In Vue 3 components, you can useuseRouterTo facilitate page navigation. Here is a simple example:

<template>
  <button @click="navigateToHome">Jump to homepage</button>
</template>
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
const navigateToHome = () => {
  ({ name: 'home' }); // Suppose you have defined a route called 'home'};
</script>

2. Listen to routing changes

Sometimes we need to perform certain operations when the route changes, such as showing or hiding certain elements. Vue 3 providesuseRouteto get the current routing status and usewatchTo listen for routing changes. Here is an example:

<template>
  <div v-if="isShow">This is a new page</div>
</template>
<script setup>
import { useRoute, watch } from 'vue-router';
import { ref } from 'vue';
const route = useRoute();
const isShow = ref(false);
watch(() => , val => {
  if (val === 'newPage') {
     = true;
  } else {
     = false;
  }
});
</script>

Summarize

With the above code, you can:

useuseRouterNavigate:

  • ImportuseRouter
  • useMethod to jump to the page.

Listen to routing changes

  • ImportuseRouteandwatch
  • usewatchMonitorchange and update component status based on the current route name.

This is the article about using vue-router to navigate and listen for routing changes in Vue 3. For more related contents of Vue 3 navigation and monitoring routing changes, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!