vue remember password function

vue remember password function

Show off

html

<van-checkbox v-model="isChecked" icon-size="16px" checked-color="#4188F2" shape="square">记住密码</van-checkbox>

data

isChecked: true, // 记住密码

created

created () {
 this.getCookie()
},
methods
// 设置cookie
            setCookie (name, pwd, exdays) {
                var exdate = new Date()// 获取时间
                exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays)// 保存的天数
                // 字符串拼接cookie
                window.document.cookie = 'userName' + '=' + name + ';path=/;expires=' + exdate.toGMTString()
                window.document.cookie = 'userPwd' + '=' + pwd + ';path=/;expires=' + exdate.toGMTString()
            },
            // 读取cookie 将用户名和密码回显到input框中
            getCookie () {
                if (document.cookie.length > 0) {
                    var arr = document.cookie.split('; ')// 这里显示的格式需要切割一下自己可输出看下
                    for (var i = 0; i < arr.length; i++) {
                        var arr2 = arr[i].split('=')// 再次切割
                        // 判断查找相对应的值
                        if (arr2[0] === 'userName') {
                            this.username = arr2[1]// 保存到保存数据的地方
                            // 其中unescape() 方法是将字符串进行编码,escape()方法是将字符串进行解码。
                        } else if (arr2[0] === 'userPwd') {
                            this.password = arr2[1]
                        }
                    }
                }
            },
// 点击登录按钮的时候,判断是否勾选了自动登录(记住密码),对cookie做相应操作
if (this.isChecked) {
  // 传入账号名,密码,和保存天数14个参数
  this.setCookie(this.ruleForm.userName, this.ruleForm.password, 14)
} else {
  // 如果没有选中自动登录,那就清除cookie
  this.setCookie('', '', -1) // 修改2值都为空,天数为负1天就好了
}

 

Guess you like

Origin blog.csdn.net/qq706352062/article/details/112003844