axios的使用例子

// http.js 

//配置axios

import axios from 'axios'
import store from './store/store'
import * as types from './store/types'
import router from './router'

// axios 配置
axios.defaults.timeout = 5000;
axios.defaults.baseURL = 'https://api.github.com';

// http request 拦截器
axios.interceptors.request.use(
    config => {
        if (store.state.token) {
            config.headers.Authorization = `token ${store.state.token}`;
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    });

// http response 拦截器
axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 401 清除token信息并跳转到登录页面
                    store.commit(types.LOGOUT);
                    router.replace({
                        path: 'login',
                        query: {redirect: router.currentRoute.fullPath}
                    })
            }
        }
        // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
        return Promise.reject(error.response.data)
    });

export default axios;

//main.js

//挂载axios

import axios from './http'

import store from './store/store'

// 将axios挂载到prototype上,在组件中可以直接使用this.axios访问
Vue.prototype.axios = axios;
new Vue({
  //加
axios,store,
})

//router.js

import store from './store/store'
import * as types from './store/types'
const routes = [
    {
        path: '/',
        name: '/',
        component: Index
    },
    {
        path: '/repository',
        name: 'repository',
        meta: {
            requireAuth: true,
        },
        component: Repository
    },
    {
        path: '/login',
        name: 'login',
        component: Login
    }
];
// 页面刷新时,重新赋值token
if (window.localStorage.getItem('token')) {
    store.commit(types.LOGIN, window.localStorage.getItem('token'))
}

const router = new VueRouter({
    routes
});

router.beforeEach((to, from, next) => {
    if (to.matched.some(r => r.meta.requireAuth)) {
        if (store.state.token) {
            next();
        }
        else {
            next({
                path: '/login',
                query: {redirect: to.fullPath}
            })
        }
    }
    else {
        next();
    }
})

export default router;

//store.js

/**
 * Created by superman on 17/2/16.
 */
import Vuex from 'vuex'
import Vue from 'vue'
import * as types from './types'

Vue.use(Vuex);
export default new Vuex.Store({
    state: {
        user: {},
        token: null,
        title: ''
    },
    mutations: {
        [types.LOGIN]: (state, data) => {
            localStorage.token = data;
            state.token = data;
        },
        [types.LOGOUT]: (state) => {
            localStorage.removeItem('token');
            state.token = null
        },
        [types.TITLE]: (state, data) => {
            state.title = data;
        }
    }
})

//api.js

/**
 * Created by superman on 17/2/16.
 */

export default {
    repo_list: '/user/repos'
}

//login.vue

methods: {
  login(){
    if (this.token) {
      this.$store.commit(types.LOGIN, this.token)
      let redirect = decodeURIComponent(this.$route.query.redirect || '/');
      this.$router.push({
        path: redirect
      })
    }
  }
}


// repository.vue

<template>
        <md-layout md-gutter v-for="repo in list">
            <md-card class="repos-card" md-with-hover>
                <md-card-header md-with-hover="true">
                    <md-card-header-text >
                        <div class="md-title">{{repo.name}}</div>
                        <div class="md-subhead">{{repo.description}}</div>
                    </md-card-header-text>
                    <md-card-media>
                        <img :src="repo.owner.avatar_url" alt="People">
                    </md-card-media>
                </md-card-header>
            </md-card>
        </md-layout>
</template>

<script type="application/ecmascript">
    import api from './constant/api'
    import * as types from './store/types'

    export default {
        name: '',
        data () {
            return {
                msg: '',
                list: []
            }
        },
        mounted(){
            this.$store.commit(types.TITLE, 'Your Repositories');
            this.getRepository();
        },

        methods: {
            getRepository(){
                let params = {
                    sort: 'updated'
                }
                this.axios.get(api.repo_list, params)
                    .then(response => {
                        this.list = response.data;
                    })
            }
        }
    }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值