vue3 watch监控从路由从哪个页面跳转来的
时间: 2023-07-25 07:38:13 浏览: 49
你可以使用 `watch` 监听 `$route` 对象的变化,其中 `$route` 对象包含了当前路由的信息。你可以在 `$route` 对象中使用 `from` 属性获取路由跳转前的路由信息,例如:
```javascript
watch: {
'$route': {
handler: function (to, from) {
console.log('从', from.path, '跳转到', to.path)
console.log('从', from.name, '跳转到', to.name)
},
immediate: true
}
}
```
在上面的代码中,`handler` 函数接受两个参数 `to` 和 `from`,分别表示跳转后的路由信息和跳转前的路由信息。你可以通过 `from.path` 或 `from.name` 获取跳转前的路由路径或名称。
相关问题
vue3+ts watch监控从路由从哪个页面跳转来的
对于 Vue3 + TypeScript 项目,你可以使用 `watch` 监听 `$route` 对象的变化,其中 `$route` 对象包含了当前路由的信息。你可以在 `$route` 对象中使用 `from` 属性获取路由跳转前的路由信息,例如:
```typescript
import { defineComponent, onMounted, watch } from 'vue'
import { RouteLocationNormalized } from 'vue-router'
export default defineComponent({
name: 'YourComponent',
setup() {
onMounted(() => {
watch(
() => $route,
(to: RouteLocationNormalized, from: RouteLocationNormalized) => {
console.log('从', from.path, '跳转到', to.path)
console.log('从', from.name, '跳转到', to.name)
},
{ immediate: true }
)
})
}
})
```
在上面的代码中,我们使用 `watch` 函数监听 `$route` 对象的变化,其中 `to` 和 `from` 参数类型均为 `RouteLocationNormalized`,表示跳转后的路由信息和跳转前的路由信息。你可以通过 `from.path` 或 `from.name` 获取跳转前的路由路径或名称。需要注意的是,在 TypeScript 中,需要先引入 `RouteLocationNormalized` 类型。
vue3路由跳转当前页面不刷新
vue3中,当路由跳转时,参数不同但路径相同时,页面不会刷新。可以通过在`<router-view>`标签上添加`key`属性来解决这个问题。当`key`属性的值不同时,页面就会重新渲染。
具体的代码如下所示:
```html
<template>
<router-view :key="route.fullPath"></router-view>
</template>
<script>
import { useRoute } from 'vue-router'
export default {
setup() {
const route = useRoute()
return {
route
}
}
}
</script>
```
另外,在`watch`中监听路由的变化,当路由发生变化时可以执行相应的逻辑。例如:
```javascript
import { useRoute, watch } from 'vue'
const route = useRoute()
watch(route, (newValue, oldValue) => {
console.log('路由已触发变化', newValue, oldValue)
// 执行相应的逻辑
})
```
以上两种方法都可以解决vue3路由跳转当前页面不刷新的问题。个人建议选择第一种方法,更加方便快捷。