vue router和vuex和request工具类

vue router和vuex和request工具类,第1张

路由
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('../views/main.vue')
  }
]

const router = new VueRouter({
  routes
})

//全局路由
// router.beforeEach((to,from)=>{
//   console.log(to)
//   console.log(from)
//   return true
// })

export default router

request工具类
import axios from 'axios'
import store from '@/store'

const ConfigBaseURL = 'http://localhost:8080'

//使用create方法创建axios实例
const request = axios.create({
    timeout: 5000,
    baseURL: ConfigBaseURL,
    // 设置Content-Type,规定了前后端的交互使用json
    // headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

request.interceptors.request.use(config => {
    
    if(store.state.token){
        console.log(store.state.token)
        config.headers['token'] = localStorage.getItem("token") == null ? '' : localStorage.getItem("token")
    }
    return config
})

request.interceptors.response.use(response => {
    let res = response.data
    if(res.code == 20000){
        return res
    }else{
        return res;
    }
})
export default request


vuex
import Vue from 'vue'
import Vuex from 'vuex'
// import user from '@/store/module/user'

Vue.use(Vuex)

export default new Vuex.Store({
  // user
  state:{
    count: 0,
    token: ''
  },
  mutations:{
    setToken(state,token){
      state.token = token
      localStorage.setItem("token",token)
    },
    addCount(state){
      state.count++
    },
    minCount(state){
      state.count--
    },
    increment(state,payload){
      state.count = state.count + payload
    },
    decrement(state,payload){
      state.count = state.count - payload
    }
  }

})

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1320249.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-11
下一篇 2022-06-11

发表评论

登录后才能评论

评论列表(0条)

保存