js--format和replace的用法和区别

在项目开发中遇到一种openApi的接口调用,也就是接口url中带有动态参数,没有了解format的用法前,都是用replace处理的,下面看实例

后台提供的接口路径:

DeleteMenuCollection: apiPath + '/menuCollection/delete/{menuId}/{menuPerson}',

这里用到了menuId和menuPerson两个动态参数。

 

使用replace方法处理如下:

1、写一个公用的方法

replace(Url, val1, val2) {
    for(let i = 0; i < val1.length; i++) {
        Url = Url.replace(val1[i], val2[i])
    }
    return Url
},

2、调用方法

this.$api.replace(this.$api.DeleteMenuCollection, ["{menuId}","{menuPerson}"], [this.componentData.menuId,this.componentData.menuPerson])

this.$api.replace这样调用方法是把replace方法写在了vue中的api.js文件中,大家可以忽略,注意参数一个或者多个都要用数组的形式

 

使用format方法处理如下:

this.$api.DeleteMenuCollection.format({menuId:this.componentData.menuId,menuPerson:this.componentData.menuPerson});

 

两种方法得到的结果一样

DeleteMenuCollection: apiPath + '/menuCollection/delete/123456/admin',

 

posted @ 2019-06-14 14:48  望兰鸟  阅读(1228)  评论(0编辑  收藏  举报