手记

vue登陆

技术点:

  • vue

  • vue-router

  • vue-resource


登陆说明: 

  1. 先获取cookie中的信息,如果存在,就直接跳转到主页,如果不存在,就转到登陆页面

  2. 登陆页面提交用户信息到服务器,服务器进行验证,返回相关信息,如果验证成功,将相关信息写入cookie,并跳转到主页。


主要代码说明:

main.js

import Vue from 'vue'import VueRouter from 'vue-router'import VueResource from 'vue-resource'...import App from './App'import routes from './router/index'import cookie from './util/cookies.js'Vue.prototype.$cookie = cookieVue.use(Vuex)Vue.use(VueResource)Vue.use(VueRouter)const router = new VueRouter({    routes})router.beforeEach((to, from, next) => {    // 判断该路由是否需要登录权限     if (to.meta.requireAuth) {        var cookie = Vue.prototype.$cookie.getCookie('user'); // beforeEach钩子注册时,vue组件还没有创建        if ( cookie != null ) {            next();         } else {            next({                path: '/login',                query: {redirect: to.fullPath}  // 将跳转的路由path作为参数,登录成功后跳转到该路由             })         }     } else {        next();     } })new Vue({  el: '#app',  store,  router,  template: '<App/>',  components: { App }})

App.vue

<template>  <div id="app">    <router-view></router-view>  </div></template><script>export default {  name: 'app',}</script>

Index.vue

<template><div>          <router-link to="/login" @click.native="logout">退出</router-link></div></template><script>export default {    methods: {        logout: function(event) {          var self = this;          self.$cookie.delCookie('user');        }    }}</script>

说明:在主页面有一个退出链接,退出时触发退出事件。根据https://router.vuejs.org/zh-cn/api/router-link.html文档说明router-link  会拦截点击事件,因些这里如果直接用@click会没有反应,这里根据vue2.0官方文档,如果要监听click事件,需要加上native修饰符。

Login.vue

<template><div class='login'>    <Form ref='formLogin' :model='formLogin' :rules='formrule'>    <Row>                <Col span="1" offset="10">用户: </Col>        <Col span="3">            <FormItem prop="user">            <Input type="text" v-model="formLogin.user" placeholder="Username">                <Icon type="ios-person-outline" slot="prepend"></Icon>            </Input>            </FormItem>        </Col>            </Row>    <Row>                <Col span="1" offset="10">密码: </Col>        <Col span="3">            <FormItem prop="password">            <Input type="password" v-model="formLogin.password" placeholder="Password">                <Icon type="ios-person-outline" slot="prepend"></Icon>            </Input>            </FormItem>        </Col>    </Row>    <Row>        <Col span="2" offset="12">                        <Button type="primary" @click="handleSubmit('formLogin')" :loading="logining">登录</Button>        </Col>    </Row>        </Form></div></template><script>export default {    data () {        return {            logining: false,            formLogin: {user:'', password:''},            formrule: {                user: [                    { required: true, message: '请填写用户名', trigger: 'blur' }                ],                password: [                    { required: true, message: '请填写密码', trigger: 'blur' },                    { type: 'string', min: 6, message: '密码长度不能小于6位', trigger: 'blur' }                ]            }        }    },    methods: {        handleSubmit(value) {            var self = this;            self.$refs[value].validate((valid) => {                if (valid) {                    self.logining = true;                    self.$http.post('/logindata', self.formLogin).then(                        resource => {                            let expireMin = 2;                            self.$cookie.setCookie('user', self.formLogin.user, expireMin);                            self.$router.push({ path: '/'});                            self.$Message.success('登录成功!');                        },                        resource => {                            return resource.status;                        }                    );                                    } else {                    self.$Message.error('表单验证失败!');                }            })        }    }} </script>

router/index.js

import Login from '@/components/Login'import Index from '@/components/Index'export default [{        path: '/login',        name: 'Login',        component: Login    }, {        path: '/',        name: 'Index',        component: Index,        meta: { requireAuth: true, }    }]

util/cookies.js

function getCookie(name) {    var reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");    if ( Array.isArray(document.cookie.match(reg))) {        var arr = document.cookie.match(reg);        return unescape(arr[2]);    }            else        return null;}function setCookie(c_name, value, expire) {    var exdate = new Date();    exdate.setMinutes(exdate.getMinutes() + expire);    document.cookie = c_name + "=" + escape(value) + ((expire == null) ? "" : ";expires=" + exdate.toGMTString());}function delCookie(name) {    var exp = new Date();    exp.setTime(exp.getTime() - 1);    var cval = getCookie(name);    console.log(exp);    if (cval != null)        document.cookie = name + "=" + cval + ";expires=" +exp.toGMTString();}export default { getCookie, setCookie, delCookie }


0人推荐
随时随地看视频
慕课网APP