Vuejs:路线更改事件

Vuejs: Event on route change

在我的主页中,我有下拉菜单,通过单击 link @click = "show=!show" 显示 v-show=show,我想在更改路线时设置 show=false。请告诉我如何实现这个东西。

在您的组件中的 $route 上设置一个 watcher,如下所示:

watch:{
    $route (to, from){
        this.show = false;
    }
} 

这会观察路由变化,当发生变化时,将 show 设置为 false

如果您使用的是 v2.2.0,那么还有一个选项可用于检测 $routes 中的变化。

要对同一组件中的参数变化做出反应,您可以观察 $route 对象:

const User = {
  template: '...',
  watch: {
    '$route' (to, from) {
      // react to route changes...
    }
  }
}

或者,使用 2.2 中引入的 beforeRouteUpdate 守卫:

const User = {
  template: '...',
  beforeRouteUpdate (to, from, next) {
    // react to route changes...
    // don't forget to call next()
  }
}

参考:https://router.vuejs.org/en/essentials/dynamic-matching.html

更新

如@CHANist 所述,router.listen 不再有效,我不知道它从哪个版本停止工作,但好消息(正如@CHANist 所述)我们可以使用:

this.$router.history.listen((newLocation) => {console.log(newLocation);})

旧回复

上面的响应更好,但为了完整起见,当你在一个组件中时,你可以访问 VueRouter 中的历史对象: 这个.$router.history. 这意味着我们可以通过以下方式收听更改:

this.$router.listen((newLocation) => {console.log(newLocation);})

我觉得这个主要是和这个一起用的时候有用。$router.currentRoute.path 您可以查看我在说什么放置 debugger

代码中的说明并开始使用 Chrome DevTools 控制台。

万一有人正在寻找如何在 Typescript 中执行此操作,这里是解决方案:

@Watch('$route', { immediate: true, deep: true })
onUrlChange(newVal: Route) {
    // Some action
}

是的,正如下面@Coops 所提到的,请不要忘记包括:

import { Watch } from 'vue-property-decorator';

编辑: Alcalyn 很好地指出了使用 Route 类型而不是使用 any:

import { Watch } from 'vue-property-decorator';    
import { Route } from 'vue-router';

具有 deep 选项的 Watcher 对我不起作用。

相反,我使用 updated() 生命周期挂钩,它会在每次组件数据更改时执行。 就像使用 mounted().

一样使用它
mounted() {
   /* to be executed when mounted */
},
updated() {
   console.log(this.$route)
}

供参考,请访问 documentation

打字稿用户的另一种解决方案:

import Vue from "vue";
import Component from "vue-class-component";

@Component({
  beforeRouteLeave(to, from, next) {
    // incase if you want to access `this`
    // const self = this as any;
    next();
  }
})

export default class ComponentName extends Vue {}

使用 Vue Router 是另一种方法,在你的组件中使用 beforeRouteLeave 方法如下:

<template>
   <button @click="ShowMethod">DisplayButton</button>
</template>
<script>
  data() {
    return { show: true };
   },
   methods: {
   ShowMethod() {
   this.show = false;
    }
   },
   beforeRouteLeave(to, from, next) {
   this.show = false;
   next();
 }
</script>

根据 VueJs 文档,它称为 Navigation Guards 检查下面的 link:

Navigation Guards

The leave guard is usually used to prevent the user from accidentally leaving the route with unsaved edits. The navigation can be canceled by calling

组件内保护:

beforeRouteEnter

beforeRouteUpdate

beforeRouteLeave

  beforeRouteLeave(to, from, next) {
// called when the route that renders this component is about to
// be navigated away from.
// has access to `this` component instance.
 }

查看下面link了解更多信息:

In-Component Guards

从“vue-router”导入{useRouter};

const router = useRouter();

router.afterEach((到, 从) => { });