vue-cli入门(四)——vue-resource登录注册实例 前言 实例功能简述 项目功能梳理 开发项目

前言

使用vue-resource请求接口非常方便,在使用前需安装vue-resource依赖并在入口文件main.js中声明。附上git地址

实例功能简述

本实例只有简单的两个模块:登录和注册,主要演示如何用vue-resource请求接口以及后期逻辑书写。各个功能如下所示:
登录模块




注册模块

项目功能梳理

在创建项目之前,我们先理一下整个项目的功能模块。
登录模块
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为后台管理页

开发项目

用vue-cli创建一个新项目,创建好后,因为我们要用到接口请求,所以第一步先安装vue-resource,打开cmd进入文件所在目录,输入npm install vue-resource,安装完成后在入口文件main.js中引入

import VueResource from 'vue-resource'
Vue.use(VueResource)

1.登录页

1.1 新建login.vue页面

在src中新建views/login/login.vue
<pre>

<template>
    <div>
        <div class="login-wrap" v-show="showLogin">
            <h3>登录</h3>
            <p v-show="showTishi">{{tishi}}</p>
            <input type="text" placeholder="请输入用户名" v-model="username">
            <input type="password" placeholder="请输入密码" v-model="password">
            <button v-on:click="login">登录</button>
            <span v-on:click="ToRegister">没有账号?马上注册</span>
        </div>

        <div class="register-wrap" v-show="showRegister">
            <h3>注册</h3>
            <p v-show="showTishi">{{tishi}}</p>
            <input type="text" placeholder="请输入用户名" v-model="newUsername">
            <input type="password" placeholder="请输入密码" v-model="newPassword">
            <button v-on:click="register">注册</button>
            <span v-on:click="ToLogin">已有账号?马上登录</span>
        </div>
    </div>
</template>

<style>
    .login-wrap{text-align:center;}
    input{display:block; width:250px; height:40px; line-height:40px; margin:0 auto; margin-bottom: 10px; outline:none; border:1px solid #888; padding:10px; box-sizing:border-box;}
    p{color:red;}
    button{display:block; width:250px; height:40px; line-height: 40px; margin:0 auto; border:none; background-color:#41b883; color:#fff; font-size:16px; margin-bottom:5px;}
    span{cursor:pointer;}
    span:hover{color:#41b883;}
</style>

<script>
    export default{
        data(){
            return{
                showLogin: true,
                showRegister: false,
                showTishi: false,
                tishi: '',
                username: '',
                password: '',
                newUsername: '',
                newPassword: ''
            }
        }
    }
</script>

</pre>

1.2 配置路由

编辑/src/router/router.js
<pre>

import Vue from 'vue'
import Router from 'vue-router'
/*引入页面*/
import Login from '@/views/login/login.vue'
import Main from '@/views/main/main.vue'
import Home from '@/views/home/home.vue'

Vue.use(Router)

/*配置路由*/
export default new Router({
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    },
    {
      path: '/main',
      name: 'Main',
      component: Main
    },
    {
      path: '/home',
      name: 'Home',
      component: Home
    }
  ]
})

</pre>

在cmd输入npm run dev启动项目,在浏览器看效果

1.3 登录功能

点击登录按钮,触发login事件,登录成功会保存cookie,所以我们先把公共方法写好。新建src/assets/js/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)
}

login.vue页面先引用该公共方法

<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>

同时新建登录成功跳转到的主页 src/views/home/home.vue

<template>
    <div>
        <h3>欢迎 {{name}}</h3>
        <a href="#" @click="quit">注销登录</a>
    </div>
</template>

<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>

1.4 测试

现在我们来检测一下,接口是我用php写在本地上的,服务器环境用的xampp,我们先打开xampp的phpMyadmin数据库管理页看一下我们的user表

用户名不存在测试

然后我们来试试刚刚写的登录功能
输入用户名“张三”,密码“123”,可以看到提示区域显示“该用户不存在”,接口返回的值是-1


密码错误测试

输入用户名“刘德华”,密码“123456”,可以看到提示区域显示“密码错误”,接口返回的值是0


登录成功测试

输入用户名“刘德华”,密码“123”,可以看到提示区域显示“登录成功”,间隔1秒自动跳转到了主页,url地址栏可以看到路由的变化,接口返回值为1,打印cookie可以看到已经存在username的cookie


cookie测试

刚刚我们已经登录成功了,并且已经保存了username的cookie,现在我们在该浏览器中新建一个标签页,输入路由localhost:8080/#/可以看到路由自动跳转到了home。这个意思就是用户登录成功之后,在cookie有效期内是可以免登录直接跳转主页的。


注销登录测试

注销登录其实就是删除cookie,可以看到打印出的cookie里面已经没有了username



此时我们已经删除了cookie,再新建一个标签页,输入主页的路由,可以看到又自动跳回登录页了


1.5 管理页

前面我们登录功能主要用到的是vue-resource的post请求,接下来我们写一个get请求,其实两者都差不多,格式都为this.$http.post/get(url,data).then((res)=>{成功返回},(res)=>{失败返回})

我们新建一个管理页src/views/main/main.vue,用get请求返回所有注册的用户

<template>
    <div>
        <h3>所有注册用户</h3>
        <ul>
            <li v-for="item in list">
                {{item.username}}
            </li>
        </ul>
    </div>
</template>

<style>
    ul{padding: 0;}
    ul li{list-style: none;}
</style>

<script>
    export default{
        data(){
            return{
                list: ''
            }
        },
        mounted(){
            this.$http.get('http://localhost/vueapi/index.php/Home/user/index').then((res)=>{
                this.list = res.data
                console.log(res)
            })
        }
    }
</script>

前面创建登录页login.vue时,我们做的判断是当用户名和密码都为admin时,认为它是管理员账号,跳转到管理页main.vue
打开登录页,输入用户名“admin”,密码“admin”,可以看到路由直接跳转到main,打印出的是接口的返回值


2.注册页

2.1 在login.vue页面控制登录注册切换

前面我们在login.vue里已经写好了登录和注册两个区域,并且我们默认的是显示登录页(即showRegister 为false,showLogin 为true),现在我们要增加切换显示的方法ToRegister和ToLogin,方法很简单,写在login.vue下script标签的methods内部即可

ToRegister(){
    this.showRegister = true
    this.showLogin = false
},
ToLogin(){
    this.showRegister = false
    this.showLogin = true
}

查看切换效果


2.2 注册功能

点击“注册”按钮,触发register事件,在该事件中将用户输入的用户名和密码传至接口

register(){
    if(this.newUsername == "" || this.newPassword == ""){
        alert("请输入用户名或密码")
    }else{
        let data = {'username':this.newUsername,'password':this.newPassword}
        this.$http.post('http://localhost/vueapi/index.php/Home/user/register',data).then((res)=>{
            console.log(res)
            if(res.data == "ok"){
                this.tishi = "注册成功"
                this.showTishi = true
                this.username = ''
                this.password = ''
                 /*注册成功之后再跳回登录页*/
                setTimeout(function(){
                    this.showRegister = false
                    this.showLogin = true
                    this.showTishi = false
                }.bind(this),1000)
            }
        })
    }
}

2.3 测试

输入用户名“蜡笔小新”,密码“labi”,提示“注册成功”,并跳转到了登录页



此时再来查看数据库,发现多了蜡笔小新的记录


好了,到这里我们已经基本实现了一个有cookie功能的简单的登录注册小实例,主要是了解一下vue-resource接口请求的用法,对代码这一块的讲解不是很多,如果了解不够的可以去看我前面的人员管理实例,在那篇文章对各个代码都有详细解释。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章