vue3监听路由变化

15,701 阅读1分钟

方式一:通过onBeforeRouteUpdate钩子

onBeforeRouteUpdate((to, from) => {
  const toRouteIndex = to.meta.index as number
  const fromRouteIndex = from.meta.index as number
  if (toRouteIndex > fromRouteIndex) {
    //设置动画名称
    transitionName.value = 'slide-left'
  } else {
    transitionName.value = 'slide-right'
  }
})

方式二:组件内部通过beforeRouteLeave钩子

//使用组件内守卫,对离开页面事件做一些操作,
beforeRouteLeave(to, from, next){
    if(from.path=='/b'){ //当前页面路由
        next({replace: true,redirect: '/a'}); //目标路由 重定向
    }else {
        next()
    }
}

方式三:通过watch监听

watch(() => route.path,(newPath, oldPath) => { console.log(newPath) },{ immediate: true });