【问题标题】:Watch changes in $route object - Vue Router观察 $route 对象的变化 - Vue Router
【发布时间】:2021-01-12 15:54:29
【问题描述】:

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

我试图通过访问$routewatch 内解决这个问题,所以每次更改路由时,我都会清除消息的状态。 警报.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

【问题讨论】:

    标签: javascript vue.js vue-router


    【解决方案1】:

    你的$route观察者设置是正确的,你的组件可以访问$route,如果你登录mounted()可以看到。

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

    【讨论】:

      猜你喜欢
      • 2021-08-30
      • 1970-01-01
      • 2017-04-29
      • 2018-01-15
      • 2017-09-07
      • 2018-07-12
      • 1970-01-01
      • 2019-12-18
      • 2015-12-17
      相关资源
      最近更新 更多