**提示:代码实验需要写到项目中,打开单页面file://存储不了cookies!**
本次代码技术栈element、vue、js-cookie、js加解密。一起讲解都在代码里面。大家如果还是不懂可以留言评论!

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>js记住密码</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
</head>
<body>
<div id="app" style="width: 600px;margin: 0 auto;margin-top: 100px;">
<h3 style="color: #333;">记住密码</h3>
<el-form :model="params" :rules="rules" ref="ruleForm" label-width="80px">
<el-form-item label="账号" prop="account">
<el-input v-model="params.account" placeholder="请输入"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="params.password" placeholder="请输入"></el-input>
</el-form-item>
</el-form>
<div style="margin-bottom: 20px;">
<el-checkbox v-model="params.remember" style="margin-left: 80px;">记住密码</el-checkbox>
</div>
<el-button type="primary" @click="submit" style="margin-left: 80px;">提交</el-button>
</div>
</body>
<script>
var app = new Vue({
el: '#app',
data: function() {
return {
params: {
account: '',
password: '',
remember: false,
},
rules: {
account: [{
required: true,
message: '请输入账号',
trigger: 'blur'
}],
password: [{
required: true,
message: '请输入密码',
trigger: 'blur'
}],
}
}
},
mounted() {
if (Cookies.get('password')) {
this.params.password = atob(Cookies.get('password')
this.params.remember=true
}
},
methods: {
submit() {
this.$refs.ruleForm.validate((valid) => {
if (valid) {
if (this.params.remember) {
var password = btoa(this.params.password)
Cookies.set('password', password)
} else {
Cookies.remove('password')
}
} else {
return false;
}
})
}
}
})
</script>
</html>