Vuejs:路线变更事件

kip*_*ris 97 vue.js vue-router vuejs2

在我的主页面中,我有v-show=show通过点击链接显示的下拉菜单,@click = "show=!show"我想show=false在我改变路线时设置.请告诉我如何实现这个目标.

Vam*_*hna 197

在组件中设置一个观察器,$route如下所示:

watch:{
    $route (to, from){
        this.show = false;
    }
} 
Run Code Online (Sandbox Code Playgroud)

这将观察路由更改,并在更改时设置show为false

  • 并使用`$ route:function(to,from){`如果你想支持旧的浏览器,并且不使用babel. (8认同)
  • 为什么有人不使用 Babel @PaulLeBeau? (2认同)

Shu*_*gam 29

如果您使用的是v2.2.0,则还有一个选项可用于检测$ routes中的更改.

要对同一组件中的params更改做出反应,您只需查看$ route对象:

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

或者,使用2.2中引入的beforeRouteUpdate防护:

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

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

  • 注意:`beforeRouteUpdate`仅适用于声明方法的视图,而不适用于任何子组件 (3认同)

Niñ*_*ura 16

具有深度选项的观察者对我不起作用。

相反,我使用了updated()生命周期钩子,每次组件的数据更改时都会执行该钩子。就像使用mount()一样使用它。

mounted() {
   /* to be executed when mounted */
},
updated() {
   console.log(this.$route)
}
Run Code Online (Sandbox Code Playgroud)

请访问文档以供您参考。


Con*_*che 14

使用 Vue3 和组合 API 你可以做到

<script setup lang="ts">
import { watch } from "vue";
import { useRoute } from "vue-router";

const route = useRoute();

// do a `console.log(route)` to see route attributes (fullPath, hash, params, path...)
watch(
  () => route.fullPath,
  async () => {
    console.log("route fullPath updated", route.fullPath);
  }
);
</script>
Run Code Online (Sandbox Code Playgroud)

此处的参考和示例: https: //router.vuejs.org/guide/advanced/composition-api.html#vue-router-and-the-composition-api


ATH*_*HER 10

以防万一有人在打字稿中寻找方法,这是解决方案

   @Watch('$route', { immediate: true, deep: true })
   onUrlChange(newVal: any) {
      // Some action
    }
Run Code Online (Sandbox Code Playgroud)

是的,正如下面@Coops所述,请不要忘记添加

import { Prop, Watch } from "vue-property-decorator";
Run Code Online (Sandbox Code Playgroud)

  • 很好的预料到这个问题。+1 (2认同)
  • 不要忘记在导入中包含:`import { Prop, Watch } from "vue-property-decorator";` (2认同)

小智 10

import {  useRouter } from "vue-router";

const router = useRouter();

router.afterEach((to, from) => { });
Run Code Online (Sandbox Code Playgroud)


Mel*_*dev 7

更新

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

this.$router.history.listen((newLocation) => {console.log(newLocation);})
Run Code Online (Sandbox Code Playgroud)

旧响应

上面的响应更好,但只是为了完整起见,当您在组件中时,您可以使用以下命令访问 VueRouter 内的历史对象:this.$router.history。这意味着我们可以通过以下方式监听变化:

this.$router.listen((newLocation) => {console.log(newLocation);})
Run Code Online (Sandbox Code Playgroud)

我认为这在与 this.$router.currentRoute.path 一起使用时主要有用您可以检查我在说什么放置 debugger

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