写在前面的话
业精于勤荒于嬉
实践是检验真理的唯一标准
项目功能梳理
登录模块
1.用户输入用户名及密码,调用接口
1.1用户名未找到,提示用户“用户名不存在”
1.2用户名找到,但密码不匹配,提示用户“密码输入错误”
1.3用户名和密码都匹配,登录成功并跳转到主页,同时将用户名存为cookie
2.加载主页获取cookie
2.1cookie不存在,跳转到登录页
2.2cookie存在,显示用户名
2.3点击注销,删除cookie并跳转到登录页
3.管理员登录
3.1输入管理员用户名及密码,跳转到管理页
注册模块
1.用户输入用户名及密码,调用接口
1.1注册成功直接跳转到登录页
cookie.js为公共方法,用于cookie的存储、获取及删除
home.vue为用户登录成功之后的主页
login.vue为登录注册页
main.vue为后台管理页
具体代码实现
项目整体文件结构如下
图片.png
cookie.js为公共方法,用于cookie的存储、获取及删除
home.vue为用户登录成功之后的主页
login.vue为登录注册页
main.vue为后台管理页
用vue-cli创建一个新项目,创建好后,因为我们要用到接口请求,所以第一步先安装vue-resource,打开cmd进入文件所在目录,输入npm install vue-resource,安装完成后在入口文件main.js中引入
import VueResource from 'vue-resource'
Vue.use(VueResource)
cookie.js
/*用export把方法暴露出来*/
/*设置cookie*/
export function setCookie(c_name,value,expire) {
var date=new Date()
date.setSeconds(date.getSeconds()+expire)
document.cookie=c_name+ "="+escape(value)+"; expires="+date.toGMTString()
console.log(document.cookie)
}
/*获取cookie*/
export function getCookie(c_name){
if (document.cookie.length>0){
let c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1){
c_start=c_start + c_name.length+1
let c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
}
/*删除cookie*/
export function delCookie(c_name){
setCookie(c_name, "", -1)
}
登录页面
<script>
import {setCookie,getCookie} from '../../assets/js/cookie.js'
export default{
mounted(){
/*页面挂载获取cookie,如果存在username的cookie,则跳转到主页,不需登录*/
if(getCookie('username')){
this.$router.push('/home')
}
},
methods:{
login(){
if(this.username == "" || this.password == ""){
alert("请输入用户名或密码")
}else{
let data = {'username':this.username,'password':this.password}
/*接口请求*/
this.$http.post('http://localhost/vueapi/index.php/Home/user/login',data).then((res)=>{
console.log(res)
/*接口的传值是(-1,该用户不存在),(0,密码错误),同时还会检测管理员账号的值*/
if(res.data == -1){
this.tishi = "该用户不存在"
this.showTishi = true
}else if(res.data == 0){
this.tishi = "密码输入错误"
this.showTishi = true
}else if(res.data == 'admin'){
/*路由跳转this.$router.push*/
this.$router.push('/main')
}else{
this.tishi = "登录成功"
this.showTishi = true
setCookie('username',this.username,1000*60)
setTimeout(function(){
this.$router.push('/home')
}.bind(this),1000)
}
})
}
}
}
}
</script>
home页面
<script>
/*引入公共方法*/
import { setCookie,getCookie,delCookie } from '../../assets/js/cookie.js'
export default{
data(){
return{
name: ''
}
},
mounted(){
/*页面挂载获取保存的cookie值,渲染到页面上*/
let uname = getCookie('username')
this.name = uname
/*如果cookie不存在,则跳转到登录页*/
if(uname == ""){
this.$router.push('/')
}
},
methods:{
quit(){
/*删除cookie*/
delCookie('username')
}
}
}
</script>
网友评论