post调用后台接口
呈现效果:
1.HTML
< template>
//这里的ruleForm在2.script -> export default -> data -> return 中定义
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="项目名称" prop="taskName">
<template>
//isTaskNameOnly:验证项目名称是否唯一的方法
<el-input v-model="ruleForm.taskName" @change="isTaskNameOnly">
//nameOK==1 项目名称唯一
<i class="el-icon-success" style="color:#9eea6a" slot="suffix" v-if="nameOK==1" ></i>
//nameOK==0 项目名称不唯一
<i v-if="nameOK==0" class="el-icon-error" style="color:#ef5858" slot="suffix"></i>
</el-input>
</template>
</el-form-item>
<el-form-item label="项目描述" prop="taskDescribe">
<el-input type="textarea" v-model="ruleForm.taskDescribe"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submit('ruleForm')">立即创建</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
</el-form>
2.script
data
return {
ruleForm: {
taskName: '', //项目名称
taskDescribe: '', //项目描述
userId: 1 //用户ID
},
nameOK: 2, //判定taskName是否可提交的键 0不可提交 1可提交
}
-
methods——isTaskNameOnly()
后端所需参数:taskName、userId
// 验证项目名称是否唯一
isTaskNameOnly() {
let that = this
//调用接口,depot为封装好的axios,这里直接用$调用即可
this.$depot.get({
url: '/isTaskNameOnly', //后端提供的接口
//前端向后端传递的参数
config: {
params: {
//data -> return -> ruleForm -> 中的taskName,用户输入后,vue会自动获取到
taskName: that.ruleForm.taskName,
//之前的登录已经将后端返回的userId保存到sessionStorage中,此处直接获取即可
userId: sessionStorage.getItem("userId")}
},
cb: (res) => {
// 我习惯在此处先consolo.log(res),将res打印出来,看看格式再对数据进行处理
// 对后端返回的数据进行处理,将res中的data加载进nameOK中nameOK会限制
that.nameOK = res.data
}
})
},
谷歌F12——
给后端传递的参数:
1. 项目名称已存在
页面下显示效果:
F12后端返回数据:
2. 项目名称不存在,可创建
页面下显示效果:
methods——submit()
后端所需参数:taskName、taskDescribe、userId
// 提交表单数据
submit() {
let that = this
let nameOK = that.nameOK //
let ruleForm = that.ruleForm //ruleForm为需要提交的表单数据
let data = that.$qs.stringify(ruleForm); //post传递数据需要用qs转化
if (nameOK != 1) {
this.$message({ message: '请按照提示正确输入信息后再创建!', center: true });
} else {
//post方法调用接口
this.$depot.post({
url: '/create', //后端提供的接口
data: data , //第一个data是封装的depot的data,冒号后面的data是我们准备好的参数
cb: (res) => {
if(res.code == 200){
//以下为数据处理
this.$message({
message: '恭喜你!项目创建成功!',
type: 'success'
});
}else{
this.$message({
message: '项目创建失败',
type: 'error'
});
}
}
})
}
},