监听$route对象的变化 - Vue Router

3

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

我尝试通过访问$route解决这个问题,在watch中清除消息的状态,以便每次路由改变时都能清除状态。 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>

main.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)
});

router.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不能被识别,我无法访问它。 需要提到的是,在我的main.js文件中,我导入了router.js文件,后者从'vue-router'中导入了Router并实例化,因此所有组件都应该能够访问$route。 有人可以解释一下原因吗?

我的项目链接:repo

1个回答

3
您的 $route 监听器设置是正确的,您的组件可以访问 $route,如果在 mounted() 中记录它,就可以看到它。
问题在于监听器位于 Alert.vue 中,该组件位于正在导航离开的页面上,因此它被销毁,防止了调用监听器。如果将 $route 监听器移动到始终保持活动状态的组件(例如 App.vue),则会发现它可以正常工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接