第
vue3和ts封装axios以及使用mock.js详解
//response
if(!params||!params.path)thrownewError(Paramsandparamsinpathcannotempty!)
//这里因为是全局的一个info,根据路由地址去请求侧边栏,所需不用把地址写死
returnrequest.postSystem.Sidebar(params.path,{routeName:params.routeName})
}
Vue文件中调用
scriptlang=tssetupname=Sidebar
import{ref,reactive,onBeforeMount}fromvue
import{info}from@/api
import{useRoute}fromvue-router
constroute=useRoute();
letloading=refboolean(false);
letsidebar=refany({});
const_fetch=async():Promisevoid={
constrouteName=route.nameasstring;
constpath=/+routeName.replace(routeName[0],routeName[0].toLocaleLowerCase())+Info
try{
loading.value=true;
constres=awaitinfo({path,routeName});
if(!res||!res.data)return;
sidebar.value=res.data;
}finally{
loading.value=false
onBeforeMount(()={
_fetch();
/script
二、mock.js的依赖安装与处理
1.安装依赖
#安装
npminstallmockjs--save
在ts中使用时,我们需要现在shims-vue.d.ts文件中去抛出模块,不然会出现引入报错的问题
/*eslint-disable*/
declaremodule*.vue{
importtype{DefineComponent}fromvue
constcomponent:DefineComponent{},{},any
exportdefaultcomponent
declaremodulemockjs;
2.新建mock所需的文件
index.ts(属于mockjs全局配置文件),mockjs/javaScript/index.ts(具体的数据文件),这两个需要关注,别的不用关注
1.新建mockjs/javaScript/index.ts(具体的数据文件)
因为我这里的数据主要是侧边栏的数据,都是固定好的,所以并没有用到mockjs的规则生成数据
import{GlobalSidebar,Sidebar}from../../sidebar;
namespaceInfoSidebar{
exporttypeInfoSidebarParams={
body:string,
type:string,
url:string
constdataSource:ArrayGlobalSidebar=[
mainTitle:JavaScript基础问题梳理,
mainSidebar:[
id:0,
hashId:This,
title:this指向,
routeName:JsBasic,
children:[
id:1,
parentId:0,
hashId:GlobalFunction,
title:全局函数
id:2,
parentId:0,
hashId:ObjectMethod,
title:对象方法
id:3,
parentId:0,
hashId:Constructor,
title:构造函数
id:4,
par