在我的主页上,我有下拉菜单,显示v-show=通过点击链接@click = "show=!当我改变路由时,我想设置show=false。请告诉我如何实现这件事。
当前回答
使用Vue路由器是另一种方法,在你的组件中使用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的文档,它被称为导航警卫,检查下面的链接:
导航警卫
左护常用于防止使用者意外 留下未保存编辑的路由。可以取消导航 通过调用
在组件警卫:
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.
}
查看下面的链接了解更多信息:
在组件警卫
其他回答
使用Vue路由器是另一种方法,在你的组件中使用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的文档,它被称为导航警卫,检查下面的链接:
导航警卫
左护常用于防止使用者意外 留下未保存编辑的路由。可以取消导航 通过调用
在组件警卫:
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上设置一个监控器,如下所示:
watch:{
$route (to, from){
this.show = false;
}
}
它观察路由变化,当路由变化时,将show设置为false
使用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>
参考资料和示例:https://router.vuejs.org/guide/advanced/composition-api.html#vue-router-and-the-composition-api
有深度选项的观察者对我没用。
相反,我使用updated()生命周期钩子,每当组件的数据发生变化时执行该钩子。 就像使用mounted()一样使用它。
mounted() {
/* to be executed when mounted */
},
updated() {
console.log(this.$route)
}
请参阅文档以供参考。
更新
如@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控制台。
推荐文章
- Vuejs:路由改变事件
- 从另一个操作中调用一个操作
- Vue项目中的视图和组件文件夹有什么区别?
- 如何在Vue2中实现反弹?
- Vue.js重定向到另一个页面
- Vuejs更新子组件的父数据
- @click和v-on的区别:点击Vuejs
- 如何从Vue数据传递一个值到href?
- forEach不是JavaScript数组的函数错误
- Vue Js -通过v循环X次(在一个范围内)
- error /node_modules/node-sass: Command failed .日志含义
- 是否有一种方法在两个命名空间的vuex模块之间分派动作?
- Vuex行动vs突变
- 在Vue.js中显示未转义的HTML
- 在Vue.js中将事件和参数传递给v-on