Vue + Element-UI 记住用户名和密码到Cookie

参考链接 https://www.cnblogs.com/nxmin/p/8386031.html

实现功能:

1.记住密码勾选,点登陆时,将账号和密码保存到cookie,下次登陆自动显示到表单内
2.不勾选,点登陆时候则清空之前保存到cookie的值,下次登陆需要手动输入

大体思路就是通过存/取/删cookie实现的;每次进入登录页,先去读取cookie,如果浏览器的cookie中有账号信息,就自动填充到登录框中,存cookie是在登录成功之后,判断当前用户是否勾选了记住密码,如果勾选了,则把账号信息存到cookie当中

示例:

template代码

  回退


  

登录页面

记住账户

 

js 代码

data() {
    return {
        checked: true,
        labelPosition: 'right',
        formLogin: {
            account: '',
            password: ''
        },

    };
},

mounted() {
    this.getCookie()
},
methods: {
    // 回退到上个页面
    back() {
        this.$router.back()
    },
    // 登陆
    loginSubmit() {
        let that = this;
        that.$axios
            .post('/option/login', {
                account: that.formLogin.account,
                password: that.formLogin.password
            })
            .then(res => {
                console.log(res);
                if ("" == res.data) {
                    console.log("登陆成功");
                    this.$message({
                        message: '欢迎登陆系统',
                        type: 'success'
                    });
                }
                this.$router.push({path: 'index'});
            })
            .catch(function (err) {
                console.log(err);
            })
    },
    // 记住用户
    rememberUser() {
        const that = this;
        //判断复选框是否被勾选 勾选则调用配置cookie方法
        if (that.checked == true) {
            //传入账号名,密码,和保存天数三个参数
            that.setCookie(that.formLogin.account, that.formLogin.password, 7);
        } else {
            //清空Cookie
            that.clearCookie();
        }
    },
    //设置cookie
    setCookie(c_name, c_pwd, exdays) {
        let exdate = new Date(); //获取时间
        exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
        //字符串拼接cookie
        window.document.cookie =
            "account" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
        window.document.cookie =
            "password" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
    },
    // 读取cookie
    getCookie: function() {
        let that = this;
        if (document.cookie.length > 0) {
            let arr = document.cookie.split("; "); //这里显示的格式需要切割一下自己可输出看下
            for (let i = 0; i < arr.length; i++) {
                let arr2 = arr[i].split("="); //再次切割
                //判断查找相对应的值
                if (arr2[0] == "account") {
                    that.formLogin.account = arr2[1]; //保存到保存数据的地方
                } else if (arr2[0] == "password") {
                    that.formLogin.password = arr2[1];
                }
            }
        }
    },
    //清除cookie
    clearCookie: function() {
        this.setCookie("", "", -1); //修改两个值都为空,天数为-1天就好了
    },
}

 

记住密码登陆后 浏览器cookie展示

Vue + Element-UI 记住用户名和密码到Cookie_第1张图片

 

 

 

你可能感兴趣的:(Vue + Element-UI 记住用户名和密码到Cookie)