如何使用Vuex在Vue.js中保护路由。

huangapple go评论123阅读模式
英文:

How to protect routes in vuejs using vuex

问题

如何在全局范围内保护路由,而不是使用这种方式,这适用于默认情况,并将没有令牌的用户重定向到登录页

这是我如何获取我的令牌

我在我的 Vuex 存储中获取令牌

英文:

How can I protect the routes globally instead of using this, this works on default and redirects users without token to login

  1. beforeRouteEnter(to, from, next) {
  2. const hasToken = localStorage.getItem('token');
  3. if (!hasToken) {
  4. next('/login'); // Redirect to the login page
  5. } else {
  6. next();
  7. }
  8. },

This is my how I get my token

  1. created() {
  2. this.getTokenFromStorage();
  3. },
  4. computed: {
  5. ...mapGetters(['currentUser', 'error', 'getToken']),
  6. },
  7. methods: {
  8. ...mapActions(['getUser', 'getTokenFromStorage']),
  9. },

I get the token in my Vuex store
如何使用Vuex在Vue.js中保护路由。

How can I just use my getToken and access it globally in Vue

答案1

得分: 2

你可以使用Vue Router中的导航守卫(Navigation Guards)来实现这一功能。这里是文档链接

  1. const router = createRouter({ ... });
  2. // 在路由器上使用`beforeEach`导航守卫
  3. router.beforeEach((to, from) => {
  4. const hasToken = localStorage.getItem('token');
  5. if (!hasToken) {
  6. return '/login'; // 重定向到登录页面
  7. }
  8. });
英文:

For that you can use Navigation Guards in Vue Router. Here's the documentation link.

  1. const router = createRouter({ ... });
  2. // use `beforeEach` navigation guard on router
  3. router.beforeEach((to, from) => {
  4. const hasToken = localStorage.getItem('token');
  5. if (!hasToken) {
  6. return '/login'; // Redirect to the login page
  7. }
  8. });

huangapple
  • 本文由 发表于 2023年5月29日 07:16:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76353944.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定