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',

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM