由于我们采用的是前后端分离的开发模式,因此我们需要进行前后端联调。我负责的是前端部分,因此我只需要完成前端需要进行的配置即可。我所使用的Vue框架现在比较主流的就是用axios模块进行网络请求,因此我就选择了这种方式。
首先在命令行中进入项目所在的文件夹,接着执行如下命令安装axios:
npm i axios -S
根据我在官网找到的例子,完成这步以后就可以直接调用axios方法了,但在我实际使用中却发现产生了报错axios is not defined
。经过查阅后发现,由于我安装的axios并不属于vue的插件,因此不能直接调用,而是需要要通过控制原型链的方式引入后使用。采用此方式需要在main.js中添加如下代码:
import axios from 'axios';
Vue.prototype.$axios = axios;
完成后,在调用时输入this.$axios
即可。
下面是一个我调用axios传送数据的例子。
submitForm() {
console.log("start post");
this.$axios({
method: "post",
url: "api/tickets",
data: {
departure: this.ruleForm.departure,
destination: this.ruleForm.destination,
goDate: this.ruleForm.date1,
backDate: this.ruleForm.date2,
trainOrPlane: this.ruleForm.radio,
trainType: this.ruleForm.type,
},
})
.then((res) => {
console.log(res.data); //在console中显示传送的数据
console.log("ok");
})
.catch((res) => {
alert("请求失败,请重试!");
});
}