【发布时间】:2021-01-12 15:54:29
【问题描述】:
我正在做一个小型 CRM 项目。在登录表单中,我有一个组件在电子邮件或密码不正确时显示警告消息。当有人尝试错误地登录,然后输入正确的信息然后注销时,除非刷新页面,否则该消息仍会出现。
我试图通过访问$route 在watch 内解决这个问题,所以每次更改路由时,我都会清除消息的状态。
警报.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