axios封装Vue+vuex项目应用,登录页

1.Vue脚手架config文件夹中的index文件中配置代理

proxyTable: {
      '/too':{
        target:'http://169.254.2.223:7001',//服务器地址
        pathRewrite:{"^/too":""},
        showOrigin:true
      }
  }

2.新建文件夹utils,index.js文件中封装axios

import axios from 'axios';
let host='/too';
const request = (method,url, option = {}) => {
    if (option.body) {
        option.body = JSON.stringify(option.body)
    }  
    let newOption = {
        headers: {
            'Content-Type': 'application/json',
            "Authorization": localStorage.getItem('token')
        },
        ...option
    };
    return axios({
        method:method,
        url: host + url,
        data: newOption
    }).then(res => {
        return res;
    }).catch(err=>{
        return err;
    })
}
export default request;

3.新建文件夹service,index.js请求接口文件

import request from '../utils';
// 获取用户名密码
export function postLoginPassword(value){
    return request('post','/student/login',value)
}

4.新建文件夹store,index.js文件

import Vue from 'vue';
import Vuex from 'vuex';
import {postLoginPassword} from '../service';
Vue.use(Vuex);
const store=new Vuex.Store({
    state:{
        code:0
    },
    getters:{
    },
    mutations:{
        increment (state,n) {
            state.code = n
        }
    },
    actions:{
        async postLoginPassword({commit},action){
            const {student_id,student_pwd}=action;
            const result=await postLoginPassword({student_id,student_pwd});
            if(result.data.code===1){
                store.commit('increment', 1)
                localStorage.setItem('key',result.data.token);
            }
        }
    }
})
window.store=store;
export default store;

5.在脚手架入口文件main.js挂载store

import store from './store';
new Vue({
  el: '#app',
  router,
  store,//挂载store
  components: { App },
  template: ''
})

6.登录页操作



你可能感兴趣的:(axios封装Vue+vuex项目应用,登录页)