vue+elementUI实现后台管理系统登录拦截 (简单思路,可根据实际项目再做修改)
html部分:
<template>
<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" style=" width: 50% !important;
margin: 0 auto;">
<el-form-item label="用户名" prop="username">
<el-input type="text" v-model="ruleForm.username" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
</el-form>
</template>
script 部分:
<script>
export default {
name: 'Login',
data() {
var username = (rule, value, callback) => {
if (value === '') {
callback(new Error('请输入用户名'));
} else {
callback();
}
};
var password = (rule, value, callback) => {
if (value === '') {
callback(new Error('请再次输入密码'));
}else {
callback();
}
};
return {
ruleForm: {username: '', password: ''}, //登录 和密码
rules: {
username: [{ validator: username, trigger: 'blur' }],
password: [{ validator: password, trigger: 'blur' }
]
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
//简单实现 把用户名和密码存下 实际开发中 要调后台接口把登录成功后返回的token 存下
window.localStorage.setItem('access-user', JSON.stringify({username:this.ruleForm.username,password:this.ruleForm.password}))
this.$router.push({
path:"/"
})
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>
index.js文件中:
router.beforeEach((to, from, next) => {
if (to.path.startsWith('/login')) {
window.localStorage.removeItem('access-user');
next()
} else {
let user = JSON.parse(window.localStorage.getItem('access-user'))
if (!user) {
next({ path: '/login' })
} else {
next()
}
}
});