详解vue2.0+axios+mock+axios(2)

// 通过axios-mock-adapter生成代理api地址 import axios from 'axios' import MockAdapter from 'axios-mock-adapter' // import { LoginUsers } from './data/user' import {users} from './data/user' export default { init() { let mock = new MockAdapter(axios); // mock success request 模拟成功请求 mock.onGet('/success').reply(200, { msg: 'success' }); // mock error request 模拟失败请求 mock.onGet('/error').reply(500, { msg: 'failure' }) // login 模拟登录接口 mock.onPost('/user/login').reply(config => { // 解析axios传过来的数据 let { username, password } = JSON.parse(config.data); return new Promise((resolve, reject) => { // 先创建一个用户为空对象 let user = null; setTimeout(() => { // 判断模拟的假数据中是否有和传过来的数据匹配的 let hasUser = users.some(person => { // 如果存在这样的数据 if (person.username === username && person.password === password) { user = JSON.parse(JSON.stringify(person)); user.password = undefined; return true; }else { // 如果没有这个person return false } }); // 如果有那么一个人 if (hasUser) { resolve([ 200, {code: 200, msg: '登录成功',user} ]); } else { // 如果没有这么一个人 resolve([ 200, {code: 500, msg: '账号错误' }]) } }, 500); }) }); // 模拟注册接口 } }

接着在mock下建立data文件夹,;里面新建user.js用来存放用户信息

/* * 用来存放一些模拟用户的数据 * */ // import Mock from 'mockjs' const users = [ { id: 1, username: 'admin', password: '123456', email: '123456@qq.com', name: '搬砖者' }, { id: 2, username: 'lytton', password: '123456', email: 'yyyyy@163.com', name: '混子' } ] export { users }

为login.vue文件增加登录方法

<script> import {requseLogin} from "../axios/api"; export default { name: "login", data () { return { account: { username: '', password: '' }, loginRules: { username: [{required: true, message: '请输入账号', trigger: 'blur'}], password: [{required: true,message: '请输入密码', trigger: 'blur'}], }, checked: true, logining: false }; }, methods: { handleLogin() { this.$refs.AccountForm.validate((valid) => { if (valid) { this.logining = true; let loginParams = { username: this.account.username, password: this.account.password } // 调用axios登录接口 requseLogin(loginParams).then(res => { // debugger; this.logining = false; // 根据返回的code判断是否成功 let { code, msg, user } = res.data; if (code === 200) { // elementui中提示组件 this.$message({ type: 'success', message: msg }); // 登陆成功,用户信息就保存在sessionStorage中 sessionStorage.setItem('user', JSON.stringify(user)); // 跳转到后台主页面 console.log('this',this) this.$router.push({ path: '/home' }) }else { this.$message({ type: 'error', message: msg, }); } }).catch(err =>{ console.log(err); }); }else { console.log('error submit!'); return false; } }) }, reset () { this.$refs.AccountForm.resetFields() }, } } </script>

当点击登录按钮后,跳转到‘/home'页面,在components文件夹下面新增home.vue文件

<template> <div > <h1>{{ msg }}</h1> </div> </template> <script> export default { name: '后台主界面', data () { return { msg: '后台主界面' } } } </script>

接下了修改router中的index.js

import Vue from 'vue' import Router from 'vue-router' // import HelloWorld from '@/components/HelloWorld' // import Home from '../components/home'; // 懒加载方式,当路由被访问的时候才加载对应组件 const Login = resolve => require(['@/components/Login'], resolve) const Home = resolve => require(['@/components/home'], resolve) Vue.use(Router) const router = new Router({ routes: [ { path: 'https://www.jb51.net/', name: 'login', component: Login }, { path: '/login', name: 'login', component: Login }, { path: '/home', name: 'home', component: Home } ] }) // 访问之前,检查是否登陆了 router.beforeEach((to, from, next) => { if(to.path.startsWith('/login')) { window.sessionStorage.removeItem('user'); next() }else { let token = window.sessionStorage.getItem('user'); if (!token) { next({path: '/login'}) }else { next() } } }); export default router

在main.js中引入mock

import Vue from 'vue' import Router from 'vue-router' // import HelloWorld from '@/components/HelloWorld' // import Home from '../components/home'; // 懒加载方式,当路由被访问的时候才加载对应组件 const Login = resolve => require(['@/components/Login'], resolve) const Home = resolve => require(['@/components/home'], resolve) Vue.use(Router) const router = new Router({ routes: [ { path: 'https://www.jb51.net/', name: 'login', component: Login }, { path: '/login', name: 'login', component: Login }, { path: '/home', name: 'home', component: Home } ] }) // 访问之前,检查是否登陆了 router.beforeEach((to, from, next) => { if(to.path.startsWith('/login')) { window.sessionStorage.removeItem('user'); next() }else { let token = window.sessionStorage.getItem('user'); if (!token) { next({path: '/login'}) }else { next() } } }); export default router

至此,运行npm run dev即可

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/8661fe7045267b6e4e50cd76bf65cd24.html