1. Use useRouter for navigation
In Vue 3 components, you can useuseRouter
To 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 providesuseRoute
to get the current routing status and usewatch
To 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:
useuseRouter
Navigate:
- Import
useRouter
。 - use
Method to jump to the page.
Listen to routing changes:
- Import
useRoute
andwatch
。 - use
watch
Monitorchange 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!