安装
$ npm install axios --save
复制代码
使用
~/nuxt.config.js
引入插件,启动中间件
plugins: ['~/plugins/api.js'],
复制代码
~/plugins/api.js
import Vue from 'vue'
import API from '~/api/index.js'
Vue.prototype.$API = API
Vue.use(API)
复制代码
~/api/index.js
import {get, post} from './http'
export default {
POST (link) {
return post(link)
},
GET (link) {
return get(link)
}
}
复制代码
~/api/http.js
创建本地语言库
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
更加不同页面添加不用的语言
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
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
this.$API.POST('').then((res) => {
console.log(res)
})
复制代码
GET
this.$API.GET('').then((res) => {
console.log(res)
})
复制代码
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)