VUE3实战笔记

202 阅读1分钟

安装配置axios

npm install axios
  • 全局配置axios(axiosConfig.ts)
import axios from 'axios';

const http = axios.create({
  // baseURL: '',
});

// 设置请求拦截器
http.interceptors.request.use(
  (req) => {
    return req;
  },
  (error) => {
    return error;
  }
);

// 设置响应拦截器
http.interceptors.response.use(
  (res) => {
    return res;
  },
  (error) => {
    return error;
  }
);

export default http;
  • 挂载到项目上(main.ts)
import http from './axios/axiosConfig';

const app = createApp(App);

app.config.globalProperties.$http = http;

安装配置mock.js

  • 安装mock.js
npm install --save mockjs
  • mock简单的学习和使用(mock/index.ts)
import Mock from 'mockjs';

Mock.setup({
  timeout: '200-2000',
});

Mock.mock(/\/api\/test/, 'get', (req: any) => {
  console.log(req);
  return {
    code: 0,
    msg: '测试成功',
    data: '',
  };
});

export default Mock;
  • 在main.ts中引入mock
import './mock'

打包配置

  • 项目根目录增加 vue.config.js
module.exports = {
  publicPath: './',
};
  • 修改路由为hash模式
const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
});

附:完整路由配置

import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: '/',
    redirect: 'login',
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/nav',
    name: 'BottomNav',
    component: () => import('../components/BottomNav.vue'),
    redirect: '/nav/index',
    children: [
      {
        path: 'index',
        name: 'Index',
        component: () => import('../views/Index.vue'),
      },
      {
        path: 'cart',
        name: 'Cart',
        component: () => import('../views/Cart.vue'),
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach((to, from, next) => {
  const token = sessionStorage.getItem('token');
  if (to.path === '/login') {
    next();
  } else {
    if (token) {
      next();
    } else {
      next('login');
    }
  }
});

export default router;