api的组合配置
router的api配置项可以是多种类型,并且可以用Array类型组合,下面一一详解。
在Router和Interceptor配置章节已经详细介绍了各个配置项,其中api配置项支持类型比较多,并且使用会比较灵活,下面通过示例说明多种配置组合的方式。
字符串类型值
{
api: '/api/articles',
handle(data) {
const list = data.articles; // data key由apiDataName配置决定
return { list };
}
}
api接口配置为一个地址,handle方法的data key按照apiDataName(apiUrl)的规则,默认取api地址的最后一个单词,即'/api/articles'中的articles。
api地址前可以使用:get :post :put :delete前缀特别指定请求方法。未指定的默认按照ctx.method来请求。
对象类型值
{
api: {
api: '/api/articles',
name: 'articleList',
series: false,
cache: false,
query() { //... },
body() { // ... },
handle() { // ... }
},
handle(data) {
const list = data.articleList; // data key优先由api.name配置决定
return { list };
}
}
api配置为对象,可以设置name项,handle方法的data key优先以name命名,否则使用apiDataName配置的规则生成。
api对象可拥有部分router对象的同名属性,其中api.name为独有,api.handle方法仅处理当前api接口返回的数据。api.handle方法返回的数据会传入router.handle继续处理。对于一个路由只有一个api接口的情况下,无需配置两个handle处理方法。
数组类型值
{
api: [
'/api/article/detail',
{
api: '/api/user/info',
name: 'userInfo',
series: true,
handle(data, ctx) {
return data;
}
},
{
api: '/api/author/info',
query(ctx) {
return { id: ctx.query.articleId }
},
handle(data, ctx) {
return data;
}
},
(ctx) => {
if (ctx.query.commentShow) {
return '/api/comments'
}
return null;
},
(ctx) => {
return {
api: '/api/relation-articles',
name: 'articles'
}
}
],
query(ctx) {
return {
userId: ctx.query.id,
articleId: ctx.query.aid
}
},
handle(data) {
const articleDetail = data.detail;
const userInfo = data.userInfo;
const author = data.info;
const comments = data.comments || [];
const relationArticles = data.articles;
return { articleDetail, userInfo, author, comments, relationArticles };
}
}
当api为Array类型,Array item可以是String、 Object、 Function三种类型的集合,适用于一个路由有多个api接口提供数据的情况。其中Function类型只能返回String、Object两种类型值,可以为null值,表示不请求api接口。
函数类型值
{
api(ctx) {
const apis = [];
if (ctx.query.show) {
apis.push('/api/show/v3');
}
apis.push({
api: '/api/list/v3',
name: 'list'
});
return apis;
}
}
当api为Function类型,可以返回以上3种类型,接收ctx为参数。使用Function类型,可以加入某些业务逻辑判断,从而有选择的返回相应api接口。
Last updated
Was this helpful?