安装
1
| $ npm install axios --save
|
使用
~/nuxt.config.js
引入插件,启动中间件
1
| plugins: ['~/plugins/api.js'],
|
~/plugins/api.js
1 2 3 4 5
| import Vue from 'vue' import API from '~/api/index.js' Vue.prototype.$API = API Vue.use(API)
|
~/api/index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| * api接口统一管理 * import API from 'API' * Vue.prototype.$API = API * Vue.use(API) * * this.$API.Login() */ import {get, post} from './http' export default { POST (link) { return post(link) }, GET (link) { return get(link) } }
|
~/api/http.js
创建本地语言库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| import axios from 'axios' import qs from 'qs' import { baseUrl } from './env.js' const TOKEN = '7bf2b13020e1ed2278db4bba3f5e7a53102cbc37' axios.defaults.timeout = 5000 axios.defaults.baseURL = baseUrl axios.defaults.headers.common['Authorization'] = `token ${TOKEN}` axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' axios.interceptors.request.use((config) => { if (config.method === 'post') { config.data = qs.stringify(config.data) } let URL = config.url.split(config.baseURL) return config }, (error) => { return Promise.reject(error) }) axios.interceptors.response.use((res) => { return res.data }, (error) => { return Promise.reject(error) }) export const get = (url, showLoading) => axios.get(url, { showLoading: showLoading }) export const post = (url, params, showLoading) => axios.post(url, params, { showLoading: showLoading })
|
~/api/env.js
更加不同页面添加不用的语言
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| * 配置编译环境和线上环境之间的切换 * * baseUrl: 域名地址 * routerMode: 路由模式 * imgBaseUrl: 图片所在域名地址 * */ let baseUrl let routerMode const imgBaseUrl = 'https://fuss10.elemecdn.com' if (process.env.NODE_ENV === 'development') { baseUrl = 'https://api.github.com/' routerMode = 'hash' } else { baseUrl = 'https://api.github.com/' routerMode = 'hash' } export { baseUrl, routerMode, imgBaseUrl }
|
~/store/index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import Locale from '~/locales' export const state = () => ({ locales: Locale(), locale: Locale()[0] }) export const mutations = { SET_LANG(state, locale) { if (state.locales.indexOf(locale) !== -1) { console.log(locale) state.locale = locale } } }
|
方法
POST
1 2 3
| this.$API.POST('').then((res) => { console.log(res) })
|
GET
1 2 3
| this.$API.GET('').then((res) => { console.log(res) })
|