vue ajax登入,vue+vuex+axios 实现简单登录

1.创建vue项目

2.创建登录页

在views下创建一个login.vue文件 -文件内容一个简单登录页

import { mapActions } from 'vuex'

export default {

data(){

return{

data:{

username:'123456',

password:'123456',

}

}

},

methods:{

...mapActions([

'handleLogin',

'getUserInfo'

]),

login(){

this.handleLogin(this.data).then(res => {

this.getUserInfo().then(res => {

this.$router.push({ name: 'Home'})

})

}).catch(error => {

console.log(2222)

})

}

}

}

button{

margin-top: 50px;

width: 300px;

height: 50px;

}

input{

margin-top: 30px;

border: red 1px solid;

width: 500px;

height: 50px;

text-align: center;

}

3配置路由---新添加一个路由

import Vue from 'vue'

import VueRouter from 'vue-router'

import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [

{

path: '/login',

name: 'Login',

component: () => import('../views/Login.vue')

},

{

path: '/',

name: 'Home',

component: Home

},

{

path: '/about',

name: 'About',

// route level code-splitting

// this generates a separate chunk (about.[hash].js) for this route

// which is lazy-loaded when the route is visited.

component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')

}

]

const router = new VueRouter({

routes

})

export default router

4.配置ajax和储存Token

创建文件api/user.js 内容

import axios from '@/libs/api.request'

//登录请求获取token

export const login = ({ username, password }) => {

const data = {

username,

password

}

return axios.request({

url: 'login',

data,

method: 'post'

})

}

//通过token获取用户信息

export const getUserInfo = (token) => {

return axios.request({

url: 'me',

params: {

token

},

method: 'post'

})

}

//退出登录

export const logout = (token) => {

return axios.request({

url: 'logout',

method: 'post'

})

}

创建libs文件夹---下面三个文件

文件一 api.request.js

import HttpRequest from '@/libs/axios'

import config from '@/config'

const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

const axios = new HttpRequest(baseUrl)

export default axios

文件二 axios.js

import axios from 'axios'

import router from '@/router'

import { setToken, getToken, clearToken } from '@/libs/util'

class HttpRequest {

constructor (baseUrl = baseURL) {

this.baseUrl = baseUrl

this.queue = {}

}

getInsideConfig () {

const config = {

baseURL: this.baseUrl,

headers: {

Authorization: getToken()

}

}

return config

}

interceptors (instance, url) {

// 请求拦截

instance.interceptors.request.use(config => {

return config

}, error => {

return Promise.reject(error)

})

// 响应拦截

instance.interceptors.response.use(res => {

const { data, status } = res

return { data, status }

}, error => {

let { data, status } = error.response

if (status === 401) {

clearToken()

router.push({

name: 'login'

})

}

return Promise.reject(error)

})

}

request (options) {

const instance = axios.create()

options = Object.assign(this.getInsideConfig(), options)

this.interceptors(instance, options.url)

return instance(options)

}

}

export default HttpRequest

文件三 util.js

// cookie保存的天数

import config from '@/config'

export const TOKEN_KEY = 'access_token'

export const setToken = (token) => {

if (token && token.indexOf('Bearer') === -1) token = 'Bearer ' + token

sessionSave(TOKEN_KEY, token)

}

export const clearToken = () => {

sessionStorage.removeItem(TOKEN_KEY)

}

export const getToken = () => {

const token = sessionRead(TOKEN_KEY)

if (token) return token

else return false

}

// 添加修改session和读取session

export const sessionSave = (key, value) => {

sessionStorage.setItem(key, value)

}

export const sessionRead = (key) => {

return sessionStorage.getItem(key) || ''

}

export const setTitle = (routeItem, vm) => {

const handledRoute = getRouteTitleHandled(routeItem)

const pageTitle = showTitle(handledRoute, vm)

const resTitle = pageTitle ? `${title} - ${pageTitle}` : title

window.document.title = resTitle

}

在store下创建 module/user.js

import {

login,

getUserInfo,

} from '@/api/user'

import { setToken, getToken } from '@/libs/util'

export default {

state: {

username: '',

},

mutations: {

setToken (state, token) {

state.token = token

setToken(token)

},

},

actions: {

// 登录

handleLogin ({ commit }, { username, password }) {

username = username.trim()

return new Promise((resolve, reject) => {

login({

username,

password

}).then(res => {

const data = res.data

commit('setToken', data.access_token)

resolve()

}).catch(err => {

reject(err)

})

})

},

// 获取用户相关信息

getUserInfo ({ state, commit }) {

return new Promise((resolve, reject) => {

try {

getUserInfo(state.token).then(res => {

const data = res.data

// commit('setAvatar', data.avatar)

// commit('setUserName', data.name)

commit('state', data.usename)

resolve(data)

}).catch(err => {

reject(err)

})

} catch (error) {

reject(error)

}

})

},

}

}

修改store/index.js

import Vue from 'vue'

import Vuex from 'vuex'

import user from './module/user'

Vue.use(Vuex)

export default new Vuex.Store({

state: {

},

mutations: {

},

actions: {

},

modules: {

user,

}

})

创建config/index.js ----用处存放请求路径

export default {

baseUrl: {

dev: 'http://laravel7.com/api/auth/',

pro: 'http://server.fd.qytzj.com/api/admin/'

}

}

这一六十三招下来就完成了! 跳页面没写! 除了磕碜了点基本没啥问题!

点击登录

image.png

image.png

你可能感兴趣的:(vue,ajax登入)