乐闻世界logo
搜索文章和话题

How do I get current route in onMounted on page refresh?

1个答案

1

In Vue 3, when using Vue Router, if you want to retrieve the current route information within the onMounted lifecycle hook of a component, you can access the route object via the useRoute composable provided by Vue Router. This composable provides all information about the current route, such as the path and query parameters.

Here is a specific example demonstrating how to retrieve route information within the onMounted hook of a Vue 3 component:

javascript
<template> <div> <h1>Current page path is: {{ currentPath }}</h1> </div> </template> <script> import { onMounted, ref } from 'vue' import { useRoute } from 'vue-router' export default { setup() { const currentPath = ref('') const route = useRoute() onMounted(() => { // Retrieve the current route path currentPath.value = route.path console.log('Current route object:', route) }) return { currentPath } } } </script>

In this example, I used Vue 3's Composition API. The setup function is a new component option for implementing the Composition API. By leveraging the useRoute hook from Vue Router, you can access the current route object within any component. Within onMounted, you can then access route.path to retrieve the current path and store it in a reactive reference currentPath for display in the template.

This approach ensures that upon page reload, after the component is mounted, the current route information is logged to the console and the displayed path is updated on the page. This is particularly useful for scenarios where you need to adjust the UI or execute other logic based on route changes.

2024年11月20日 23:06 回复

你的答案