在我的主页上,我通过单击链接 @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
beforeRouteUpdate
仅适用于声明该方法的视图,不适用于任何子组件
以防万一有人在 Typescript 中寻找如何做到这一点,这里是解决方案:
@Watch('$route', { immediate: true, deep: true })
onUrlChange(newVal: Route) {
// Some action
}
是的,正如下面@Coops 提到的,请不要忘记包括:
import { Watch } from 'vue-property-decorator';
编辑:Alcalyn 提出了一个非常好的使用 Route 类型而不是使用任何类型的观点:
import { Watch } from 'vue-property-decorator';
import { Route } from 'vue-router';
import { Prop, Watch } from "vue-property-decorator";
import { Route } from 'vue-router';
中的界面 Route
而不是使用 any
类型
具有深度选项的观察者对我不起作用。
相反,我使用 updated() 生命周期钩子,每次组件的数据更改时都会执行该钩子。就像使用mounted() 一样使用它。
mounted() {
/* to be executed when mounted */
},
updated() {
console.log(this.$route)
}
供您参考,请访问 documentation。
更新
正如@CHANist 所说,router.listen
不再有效,我不知道它从哪个版本停止工作,但好消息(正如@CHANist 所说)是我们可以使用:
this.$router.history.listen((newLocation) => {console.log(newLocation);})
旧回应
上面的响应更好,但只是为了完整性,当你在一个组件中时,你可以通过 this.$router.history 访问 VueRouter 中的历史对象。这意味着我们可以通过以下方式监听变化:
this.$router.listen((newLocation) => {console.log(newLocation);})
我认为这在与 this.$router.currentRoute.path 一起使用时主要有用。您可以查看我所说的放置 debugger
代码中的指令并开始使用 Chrome DevTools 控制台。
listen
函数不可用。
this.$router.history.listen((newLocation) =>{console.log(newLocation);})
才能使其工作。感谢你的回答。
从“vue-router”导入 { useRouter };
常量路由器 = useRouter();
router.afterEach((to, from) => { });
打字稿用户的另一种解决方案:
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 after 方法,如下所示:
<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,请查看以下链接:
离开守卫通常用于防止用户意外离开未保存的编辑的路线。可以通过调用取消导航
组件内防护:
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.
}
查看以下链接以获取更多信息:
不定期副业成功案例分享
$route: function(to, from) {
。