vue3使用localStorage实现登录注册

也许我们使用过vuex实现过登录注册,但是我们会发现,vuex一但刷新,就会被消除,于是我们就使用网页的存储方式localStorage的方式进行存储。

首先我们要构造一个vue3的项目。目录创建如下,红色区域为需要修改的地方

vue3使用localStorage实现登录注册_第1张图片

App.vue如下




接着去配置路由,router下面的index.js

import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import login from '../views/login.vue'
const routes = [
  {
    //这里需要将根目录默认为Home,方便实现用户在保持登录 状态下再次登录时直接跳转至主页面
      path:"/",
      redirect:{
        name:"HomeView"
      }
    },
    {
      path: "/HomeView",
      name: "HomeView",
      component: HomeView,
    },
    {
      path: "/login",
      name: "login",
      component:login
      
    }
    ,{
      path: "/regester",
      name: "regester",
      component: () =>
        import("../views/regester.vue")
    }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach((to,from,next)=>
{
  //登录及注册页面可以直接进入,而主页面需要分情况
  if(to.path=='/login')
  {
    next();
    console.log(localStorage.s);
  }
  else if(to.path=='/regester')
  {
    next();
  }
  else
  {
    if(from.path=="/login")//从登录页面可以直接通过登录进入主页面
    {
      next();
    }
    else{
        //从/进入,如果登录状态是true,则直接next进入主页面
          if(localStorage.s === "true")
            {
              next();
              console.log(localStorage['s'])
            }
        else {//如果登录状态是false,那么跳转至登录页面,需要登录才能进入主页面
          next('/login');
          console.log("需要登录")
        }
    }
  }
})


export default router

接着我们来看登录,login.vue






然后是注册界面,regester.vue






最后是展示信息的页面,HomeView.vue








我们来看效果图:

vue3使用localStorage实现登录注册_第2张图片

vue3使用localStorage实现登录注册_第3张图片

好啦,其实登录注册的形式有很多种,可以是根据后端,也可以采用node.js中端形式,也可以用vuex临时存储~

你可能感兴趣的:(vue,前端,vue)