这两天老是有兄弟问到Vue的登陆和注册,登陆成功留在首页,没有登录回到登录页面,现在我用最简单实用的方法实现(两分钟技就看懂)

其实登录注册,并且登录一次保持登录的状态,是每个项目都需要实现的功能。 网上也有很多的方法,不过,不是通俗易懂,在这里说一下我自己的方法,非常简单实用
核心就是用localStorage存、取数据,这样当刷新浏览器,或者关闭在打开的时候能达到预期想要的效果


在router/index.js中

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export default new Router({
routes: [
    {path:'/', redirect:'/home'},
    {path:'/login',name:'登录',component:resolve =>{require(['@/components/login'],resolve)}},
    {path:'/home',name:'首页',component:resolve =>{require(['@/components/home'],resolve)}}
    ]
})

其中redirect(默认跳转)可以直接写在home页面,刚进入页面直接跳转首页

然后我们在home.vue的 周期函数created里面做判断 Login的值状态(Login是在login.vue中localStorage存入的变量,现在我们先读取)

      created() {
            console.log(localStorage.getItem("Login"));
            if(localStorage.getItem("Login")){
                console.log("登录过了");//登录成功了,保留在登录页面   
            }else{
                console.log("没有登录");
                this.$router.push("/login");//没有登录过 返回登录页面
            }
          },

然后我们在login.vue 当用户请求数据成功的时候把Login的状态写入

      axios.post("后台接口",qs.stringify({
                      username:"用户名",
                     password: "密码"
                        }),{
            headers: {//请求头
                "Content-Type": "application/x-www-form-urlencoded",
                "Accept":"application/json"
                }
            }).then((response) => {//成功回调
                if(response.data.status=="200"){//状态正常的时候
                      this.$router.push("/home");
         //存储名字为Login值为true的变量,方便我们在home页面判断是否登录
                      localStorage.setItem("Login",true)
              }
                    }, (error) => {
                        console.log(error);
                    });

如果首页有退出登录按钮,那退出的时候执行

         out(){
                  localStorage.removeItem("Login");//删掉我们存的变量就可以了
                  this.$router.push("/login");//点击退成功按钮返回登录页面
              }

这样就实现了Vue的登陆和注册,用户刷新浏览器,或者关闭在打开都保持登录状态

怎么样是不是很简单呢?

猜你喜欢

转载自www.cnblogs.com/jlfw/p/11863629.html