在我的主页上,我有下拉菜单,显示v-show=通过点击链接@click = "show=!当我改变路由时,我想设置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
其他回答
使用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.
}
查看下面的链接了解更多信息:
在组件警卫
你可以使用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
})
如果您正在使用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
在组件的$route上设置一个监控器,如下所示:
watch:{
$route (to, from){
this.show = false;
}
}
它观察路由变化,当路由变化时,将show设置为false
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 {}
推荐文章
- 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