在我的主页上,我有下拉菜单,显示v-show=通过点击链接@click = "show=!当我改变路由时,我想设置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 {}
其他回答
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 {}
你可以使用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
})
有深度选项的观察者对我没用。
相反,我使用updated()生命周期钩子,每当组件的数据发生变化时执行该钩子。 就像使用mounted()一样使用它。
mounted() {
/* to be executed when mounted */
},
updated() {
console.log(this.$route)
}
请参阅文档以供参考。
使用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
如果有人正在寻找如何在Typescript中做到这一点,这里是解决方案:
@Watch('$route', { immediate: true, deep: true })
onUrlChange(newVal: Route) {
// Some action
}
是的,正如下面@Coops提到的,请不要忘记包括:
import { Watch } from 'vue-property-decorator';
编辑: Alcalyn提出了一个很好的观点,使用Route type而不是any:
import { Watch } from 'vue-property-decorator';
import { Route } from 'vue-router';
推荐文章
- Vuex -传递多个参数突变
- VueJS有条件地为元素添加属性
- 如何设置URL查询参数在Vue与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模块之间分派动作?