├── api
│ └── api.js //在这个文件导入router/index.js文件就会造成LocationList.vue这个组件不加载
├── App.vue
├── components
│ ├── Footer.vue
│ ├── Header.vue
│ ├── LocationList.vue // 这里调用了api.js的方法
│ ├── Location.vue
│ └── pipeline.vue
├── router
│ └── index.js //感觉是不是这里出了问题,但是又没有报错,也找不到原因是什么
# api/api.js
import axios from 'axios'
import store from '../store/store'
// import router from '../router' <- 这里注释去掉之后就会出现问题
axios.interceptors.request.use(
config => {
if (store.state.userInfo.token) {
config.headers.Authorization = `JWT ${store.state.userInfo.token}`
console.log('request.interceptors token: ' + store.state.userInfo.token)
}
return config
},
err => {
return Promise.reject(err)
})
axios.interceptors.response.use(
response => {
console.log('api/api.js, response: ' + response)
return response
},
error => {
let res = error.response
console.log(res)
switch (res.status) {
case 401:
console.log(res)
// console.log(router.currentRoute) <- 这里注释去掉之后就会出现问题
}
return Promise.reject(error.response.data)
})
let host = 'http://127.0.0.1:8000/api'
export const apiFetchLocations = () => { return axios.get(`${host}/location/`) }
export const deployPipeline = params => { return axios.post(`${host}/pipeline/`, params) }
export const apiLogin = params => { return axios.post(`${host}/login/`, params) }
# router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../components/login/login'
import LocationList from '../components/LocationList'
import pipeline from '../components/pipeline'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
{
path: '/',
name: 'index',
component: LocationList,
meta: {
requireAuth: true
}
},
{
path: '/login',
name: 'login',
component: login,
meta: {
requireAuth: true
}
},
{
path: '/pipeline',
name: 'pipeline',
component: pipeline,
meta: {
requireAuth: true
}
}
]
})
export default router
# components/LocationList.vue
<template>
...
</template>
<script>
import ClipLoader from 'vue-spinner/src/ClipLoader.vue'
import Location from './Location.vue'
import { apiFetchLocations } from '../api/api' //这里是一次调用,应该是api.js报错造成了这个组件没有加载
export default {
data () {
return {
loading: true,
locations: [],
spincolor: '#007bff',
size: '45px'
}
},
components: { ClipLoader, Location },
created () {
this.fetchLocations()
},
methods: {
fetchLocations () {
this.loading = true
apiFetchLocations().then((response) => {
console.log('Locationlist.vue:' + response)
this.locations = response.data.results
this.loading = false
}).catch(function (error) {
console.log(error)
})
},
deployAll () {
var locations = this.$children
console.log(this.$children)
// TODO This is hacker way to trigger children's action
for (var i = 1; i < locations.length; i++) {
locations[i].deploy()
}
}
}
}
</script>
你为什么会需要在api.js里导入路由,路由一般都是在入口文件里加载么?
如果你需要做权限控制,那么应该在每个路由的beforeEach里处理,或者在ajax的response处理