axios传递参数
在请求接口的过程中,传递参数是必不可少的,本节讲解 axios 传递参数。
参数为 id:100。
请求方式为 get。
代码如下。
export default {
name: "HelloWorld",
data() {
return {};
},
methods: {
getParams() {
this.$axios.get("http://longlink.mm2018.com:8086/selectDemo", {
params: {
id: 100
}
})
.then(res => {
console.log(res);
});
}
},
created() {
this.getParams();
}
};
代码解析如下。
this.$axios.get 方法中的第一个参数是请求地址,第二个参数是用户要传递的参数。
axios 通用形式:axios 提供了一种通用形式,无论是 get 请求、post 请求还是其他请求都可以使用,这种通用形式也是在后期项目开发中首选的,代码如下。
export default {
name: "HelloWorld",
data() {
return {};
},
methods: {
getAll() {
this.$axios({
methods: "get",
url: "http://longlink.mm2018.com:8086/selectDemo?id=100",
data: {} // 如果是 post 请求,参数在 data 中
})
.then(res => {
console.log(res);
});
}
},
created() {
this.getAll();
}
};
代码解析如下。
使用通用形式,就是在 this.$axios 方法中传入配置对象,在对象中设置请求方式、接口地址、请求参数等。
axios 的使用方法相对简单,但却是项目中必不可少的,后面会通过项目实战巩固 axios 的各种使用方法。