前后端分离项目(七):实现"添加"功能(前端视图)
好家伙,本篇用于测试"添加"接口,为后续"用户注册"功能做铺垫
(完整代码在最后)
我们要实现"添加"功能
老样子我们先来理清一下思路,
现在,我是一个用户,我来到了注册页面,我在一个① 表单 中要把我要添加的 数据填好 ,
然后点击添加按钮,进行② 数据校验 (看看用户有没有少填的数据),
随后,③ 发送网络请求,把数据传到后端 ,后端再把数据传到数据库中,
最后,④ 重置表单
大概是这么回事
老样子,我们先去饿了么偷点东西
拿个表单,然后该删的删,最后留下序号,书名,作者三行以及两个按钮就好
1.前端基本视图
代码如下:
2.数据校验方法
验证规则如下
rules: { id :[
{ required: true , message: ' ID不能为空 ' , trigger: ' blur ' }
],
name: [
{ required: true , message: ' 图书名称不能为空 ' , trigger: ' blur ' }
],
author:[
{ required: true , message: ' 作者不能为空 ' , trigger: ' blur ' }
]
}
2.1.
required: true ,
不可为空
2.2.
trigger: ' blur '
失去焦点时进行校验
3.点击"添加"",发起网络请求
submitForm(formName) {
const _this = this
this.$refs[formName]. validate((valid) => { if (valid) {
axios.put( 'XXX/XXX/XXX ' ,this.ruleForm). then ( function ( resp ){ if (resp.data == ' success ' ){
_this.$alert( ' 《 ' +_this.ruleForm.name+ ' 》修改成功! ' , ' 消息 ' , {
confirmButtonText: ' 确定 ' ,
callback: action => {
_this.$router.push( ' /.... ' )
}
})
}
})
} else {
return false ;
}
});
},
3.1.validate()方法
说明:这是一个校验方法,vue组件库element-ui 的validate方法_moni110的博客-CSDN博客_elementui validate
validate()时elment-ui封装好的用于对整个表单进行验证
somethig.validate((valid) => { if {valid}()
}
其中的valid是布尔值,为true时表示校验通过。
调用validate()校验时,需要prop属性绑定校验项的字段名
如果prop属性不绑定name这个字段名,表单校验时,不会校验变量ruleForm.name 的值。
3.2.resp接受"网络请求"的返回值
成功了就谈个窗,告诉你成功了
失败了就,...就寄
4.重置表单方法:
resetForm(formName) {
this.$refs[formName]. resetFields();
}
4.1.
resetFields();
这是组件里面官方的表单重置方法,(以前用这个方法次次寄,这次居然能用了)
5.该部分完整代码如下:
<template>
<el-form style= " width: 60% " :model= " ruleForm " :rules= " rules " ref= " ruleForm " label-width= " 100px " class= " demo-ruleForm " >
<el-form-item label= " 图书编号 " prop= " id " >
<el-input v-model= " ruleForm.id " ></el-input>
</el-form-item>
<el-form-item label= " 图书名称 " prop= " name " >
<el-input v-model= " ruleForm.name " ></el-input>
</el-form-item>
<el-form-item label= " 作者 " prop= " author " >
<el-input v-model= " ruleForm.author " ></el-input>
</el-form-item>
<el-form-item>
<el-button type= " primary " @click= " submitForm('ruleForm') " >修改</el-button>
<el-button @click= " resetForm('ruleForm') " >重置</el-button>
</el-form-item>
</el-form>
</template>
<script> export default {
data() {
return {
ruleForm: { id : '' ,
name: '' ,
author: '' },
rules: {
name: [
{ required: true , message: ' 图书名称不能为空 ' , trigger: ' blur ' }
],
author:[
{ required: true , message: ' 作者不能为空 ' , trigger: ' blur ' }
]
}
};
},
methods: {
submitForm(formName) {
const _this = this
this.$refs[formName].validate((valid) => { if (valid) {
axios.put( ' http://localhost:8181/book/update ' ,this.ruleForm). then ( function (resp){ if (resp.data == ' success ' ){
_this.$alert( ' 《 ' +_this.ruleForm.name+ ' 》修改成功! ' , ' 消息 ' , {
confirmButtonText: ' 确定 ' ,
callback: action => {
_this.$router.push( ' /BookManage ' )
}
})
}
})
} else {
return false ;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
},
} </script>
后端接口还没写好,效果预览图暂无