初识
使用vue/cli搭建的项目可以在vue.config.js中,模拟一个后台(express写法) vue.config.js
configureWebpack: { devServer: { before ( app) { app. get ( '/api/login' , function ( req, res) { const { username, passwd } = req. query; console. log ( username, passwd) ; if ( username === 'admin' && passwd === '123456' ) { res. json ( { code: 1 , token: '奇怪的栗子' } ) ; } else { res. status ( 401 ) . json ( { code: 0 , message: '用户名或密码错误' } ) ; } } ) ; } }
}
前端请求.
准备 /src/service/user.js 对用户接口进行管理
import axios from 'axios' ; export default { login ( user) { return axios. get ( '/api/login' , { params: user } ) }
}
import Vue from 'vue'
import Vuex from 'vuex'
import us from './service/user' ; Vue. use ( Vuex) export default new Vuex. Store ( { state: { isLogin: false } , mutations: { setLoginState ( state, b) { state. isLogin = b; } } , actions: { login ( { commit } , user) { return us. login ( user) . then ( res => { const { code, token } = res. data; if ( code) { commit ( 'setLoginState' , true ) ; localStorage. setItem ( 'token' , token) ; } return code; } ) } } , modules: { }
} )
登录组件
login.vue 在其方法里面写(vue 2.x)
methods: { handleLogin ( e) { e. preventDefault ( ) ; this . $store. dispatch ( 'login' , this . model) . then ( code => { if ( code) { const path = this . $route. query. redirect || '/' ; this . $router. push ( path) ; } } ) . catch ( error => { const toast = this . $createToast ( { time: 2000 , txt: error. message || error. response. data. message || '登录失败' , type: 'error' } ) ; toast. show ( ) ; } ) } , }