在我的主页上,我有下拉菜单,显示v-show=通过点击链接@click = "show=!当我改变路由时,我想设置show=false。请告诉我如何实现这件事。


当前回答

你可以使用beforeEach事件,它允许任何函数在路由改变时发生,只是不要忘记调用next()函数来进行下一个操作,基本上它与后端expressJS中间件具有相同的工作。

router.beforeEach((to, from, next) => {
  store.commit('setError', null); //in this example on each route I'm removing the error noted from the old route
  document.title = `${to.meta.title} | HartWork`; //on each route I'm adding a prefix to document title.
  next(); //calling next to proceed next functions and operations
})

其他回答

更新

如@CHANist所述,路由器。listen不再工作,我不知道从哪个版本开始停止工作,但好消息是(@CHANist也说过)我们可以使用:

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

旧的响应

上面的响应是更好的,但只是为了完整性,当你在一个组件中,你可以访问VueRouter内部的历史对象: router.history美元。 这意味着我们可以通过:

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

我认为这个函数在和。$router.currentRoute.path一起使用时非常有用 您可以检查我所说的关于放置调试器的内容

指令在你的代码,并开始玩Chrome DevTools控制台。

有深度选项的观察者对我没用。

相反,我使用updated()生命周期钩子,每当组件的数据发生变化时执行该钩子。 就像使用mounted()一样使用它。

mounted() {
   /* to be executed when mounted */
},
updated() {
   console.log(this.$route)
}

请参阅文档以供参考。

import {useRouter} from vue-router;

useRouter();

路由器。afterEach((to, from) => {});

typescript用户的另一个解决方案:

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 {}

如果您正在使用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