监视对象 - Vue 路由器$route的变化



我正在做一个小型CRM项目。在登录表单中,我有一个组件,当电子邮件或密码不正确时会显示警报消息。当有人尝试错误登录,然后键入正确的信息然后注销时,除非刷新页面,否则该消息仍会显示。

我试图通过访问watch来解决这个问题$route,所以每次更改路由时,我都会清除消息的状态。 Alert.vue:

<template>
<div :class="'alert ' + alert.type">{{alert.message}}</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
computed: mapState({
alert: state => state.alert
}),
methods: mapActions({
clearAlert: 'alert/clear' 
}),
watch: {
$route (to, from){
console.log('inside $rout');
this.clearAlert();
}
}
};
</script>

主.js:

import Vue from 'vue';
import { store } from './_store';
import { router } from './_helpers';
import App from './components/App';
import './css/main.css';
new Vue({
el: '#app',
router,
store,
render: h => h(App)
});

路由器.js:

import Vue from 'vue';
import Router from 'vue-router';
import Dashboard from '../components/Dashboard.vue';
import LoginPage from '../components/LoginPage.vue';
import UserPage from '../components/UserPage.vue';
Vue.use(Router);
export const router = new Router({
mode: 'history',
routes: [
{ path: '/app', component: Dashboard },
{ path: '/login', component: LoginPage },
{ path: '/app/user-info', component: UserPage },
{ path: '*', redirect: '/app' }
]
});
router.beforeEach((to, from, next) => {
const allowedPages = ['/login'];
const authRequired = !allowedPages.includes(to.path);
const loggedIn = localStorage.getItem('user');
if (authRequired && !loggedIn) {
return next('/login');
}
next();
})

我尝试在文档中执行这两种方法 https://router.vuejs.org/guide/essentials/dynamic-matching.html

由于某种原因,$route无法识别,我无法访问它。 我还应该提到,在我的主文件中.js我导入了router.js文件,该文件从'vue-router'导入Router并实例化它,因此$route应该可以从所有组件访问。 有人可以解释一下为什么吗?

链接到我的项目:存储库

您拥有的$route观察程序设置是正确的,并且您的组件可以访问$route,如果您将其登录mounted()就可以看出。

问题是观察程序在Alert.vue中,这是一个位于正在导航离开的页面上的组件,因此它被销毁,从而阻止调用观察器。如果将$route观察程序移动到始终保持活动状态的组件(例如,App.vue),您将看到它正常工作。

最新更新