import 'babel-polyfill'
import Vue from 'vue'
import vRegion from 'v-region';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import 'font-awesome/css/font-awesome.css'
import VueRouter from 'vue-router'
import routers from './routers'
import apiFetch from './apiFetch'
import App from './App'
import Vuex from 'vuex'
import store from './vuex/store'
import axios from 'axios'
Vue.prototype.$ajax = axios
Vue.prototype.$apiFetch = apiFetch
Vue.use(VueRouter)
Vue.use(Vuex)
Vue.use(ElementUI)
Vue.use(vRegion);
const router = new VueRouter({
mode: 'history',
routes: routers
})
router.beforeEach((to, from, next) => {
if(to.meta.content){
let head = document.getElementsByTagName('head');
let meta = document.createElement('meta');
meta.content = to.meta.content;
meta.name = "viewport";
head[0].appendChild(meta)
}
if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
if (store.state.InvestorInfo) { // 通过vuex state获取当前的token是否存在
next();
}
else {
next({
path: '/login',
// query: {redirect: to.fullPath} // 将跳转的路由path作为参数,登录成功后跳转到该路由
})
}
}
else {
next();
}
})
// http request 拦截器
axios.interceptors.request.use(
config => {
if (store.state.token) { // 判断是否存在token,如果存在的话,则每个http header都加上token
config.headers.Authorization = `token ${store.state.token}`;
}
return config;
},
err => {
return Promise.reject(err);
});
// http response 拦截器
axios.interceptors.response.use(
response => {
let time=new Date().getTime()
let outTime=store.state.outTime
let lengthTime=time-outTime
if(response.data.code==10008&&lengthTime>5000){
router.replace({
path: '/login',
query: {refresh: 2}
})
store.commit('outTime',time)
}else if(response.data.code==10008){
return
}
if(response.data.code==500&&lengthTime>5000){
store.commit('outTime',time)
}else if(response.data.code==500){
return
}
return response;
},
error => {
return Promise.reject(error.response.data) // 返回接口返回的错误信息
});
var bus=new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
export default bus;