方式一、通过 getCurrentInstance 方法获取当前组件实例,从而获取 route 和 router
<template>
<div>
</div>
</template>
<script>
import { defineComponent, getCurrentInstance } from 'vue'
export default defineComponent({
name: 'About',
setup(){
const { proxy } = getCurrentInstance()
console.log(proxy.$root.$route)
console.log(proxy.$root.$router)
return {}
}
})
</script>
- 方式二:通过从路由中导入 useRoute useRouter 使用 route 和 router。 官方Api
<script lang="ts">
import { defineComponent } from 'vue'
import { useRoute, useRouter } from 'vue-router'
export default defineComponent({
setup () {
const $route = useRoute()
const $router = useRouter()
console.log($route)
console.log($router)
}
})
</script>
-
组件内导航守卫函数。 官方Api
<template> <div id="about"> <button @click="$router.push('/scroll')">goScroll</button> </div> </template> <script lang="ts"> import { defineComponent } from 'vue' export default defineComponent({ setup () { /* */ }, beforeRouteEnter (to, from, next) { // 组件导航守卫---前置守卫 console.log(to) console.log(from) next() }, beforeRouteLeave (to, from) { // 组件导航守卫---后置守卫 console.log(to) console.log(from) } }) </script>