接口传参

Posted by CodingWithAlice on August 13, 2019

接口传参

1.接口参数(必传/选传/键值对/值)

在调用接口的时候,注意传参和接收参数的形式要一致

//这是声明调用接口的方法,传递的参数是params,参数的形式是键值对形式
export const getTree = (params) => {
	return new Promise(resolve => {
        SWXHR.get('/school', {   //这里写接口地址 
                params: params
            })
            .then(res => {
               resolve(res);
          });
    });
};

在接收参数的时候,直接在方法中异步调用,同时要记得在mount里面调用this.getSchool();执行函数,方便页面初次加载的时候有数据

async getSchool() {
      let res = await getTree();
      if (res.code === "success") {
        	this.data = res.data;
      }
    }

当传递的参数可选时,接口处的参数形式应该写为{params},这样在实例组件调用的时候以该参数的属性传递/键值对的形式传递

export const getInfo = (params) => {    
	return new Promise(resolve => {        
		SWXHR.get('/member', {params})
            .then(res => {
            	resolve(res);
        	});    
    });
};
 async getInfoList() {      
     let params = {        
         Num: this.page,        
         Size: this.Size,        
         Id: this.Id,        
         Type: this.Type      };      
     if (this.name) {        
         if (/^[0-9]*$/.test(this.name) === true) {          
             params.telephone = this.name;        
         }else if(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/g.test(this.name)   
             params.email = this.name;        
         } else {          
             params.name = this.name;        
         }      
     }      
     if (this.school) {        
         params.school = this.school;      
     }      
     let res = await getInfo(params);      
     if (res.code === "success") {        
         this.data = res.data.items;             
         this.total = Number(res.data.total);      
     }    
 },

2.Chrome开发者调试工具中查看接口传递的参数

在接口调用参数的时候,一般以键值对的形式调用,可以F12Network里面,点击XHR查询参数传递了什么,根据传递的参数判断是否传递了正确参数。