直接调用element ui给我们写好的函数就可以了。 获取当前表单的实例对象,通过这个实例对象,调用给出的重置函数。 首先确认当前表单有实例对象
<el-form ref="loginref"接下来在重置按钮绑定一个事件
<el-button type="info" @click="reset">重置</el-button>接下来在行为区找到method节点,编写这个事件函数,通过this找到refs然后指向本实例对象,调用重置函数。
reset () { this.$refs.loginref.resetFields() } `运行 重置前 重置后,恢复默认
首先当预验证结果不为True时,直接返回。
if(!valid) return;验证为True时,发出请求,需要引用包,所以在入口文件main.js中
import axios from 'axios'引入后把这个包挂载到Vue的原型对象上,这样的话,每一个Vue的组件都可以通过this直接访问到http,从而发起AJAX请求。
Vue.prototype.$http = axios接下来尽量为axios配置请求的根路径,地址为后端接口所在文件夹
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'完整的引入axios代码
// 引入包 import axios from 'axios' // 配置请求的根路径 axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/' Vue.prototype.$http = axios接下来返回登陆函数继续编写预验证成功时的行为。通过this访问原型的http,发起post请求,请求地址为login(查看自己后台可知),请求时携带的参数可以直接用之前的loginform。
this.$http.post('login',this.loginform);现在的login代码
login () { this.$refs.loginref.validate((valid) => { // console.log(valid) if (!valid) return; this.$http.post('login',this.loginform); })接下来我们准备运行了,但如果要访问api接口,得保证api服务器处于运行状态。
首先启动mysql 然后找到后端文件夹,运行app.js。代开powershell窗口输入命令启动服务器 接下来再写接收的代码
login () { this.$refs.loginref.validate((valid) => { // console.log(valid) if (!valid) return const result = this.$http.post('login', this.loginform) console.log(result) }) }运行结果,输入账号密码后,会返回一个promise对象。 我们需要简化一下promise对象,可以用async,await简化。(await只能用在async修饰的方法中)
login () { this.$refs.loginref.validate(async valid => { // console.log(valid) if (!valid) return const result = await this.$http.post('login', this.loginform) console.log(result) }) }再次运行,会获取一个简化后具体对象数据 该对象共有6个属性,都是axios帮我们封装好的,**其中data是服务器返回的真实数据,我们只需要关注这个属性。**所以我们可以从这个对象上直接将data解构赋值出来。
const { data: res } = await this.$http.post('login', this.loginform) console.log(res)再次运行 可以看到,用户不存在,状态码为400,说明登陆失败。当状态码为200时,登陆是成功的。所以可以根据状态码来给用户返回相应信息。
if (res.meta.status !== 200) return console.log('用户名或密码错误') console.log('登陆成功')运行
上面的提示我们都是使用的console,用户无法看到。所以我们可以用element ui中提供的组件来进行弹窗提示。 首先要在plugins下的elements.js中引入需要的组件元素Message。
import { Button, Form, FormItem, Input, Message } from 'element-ui'它的配置方式与之前的不太一样,需要进行全局挂载。将弹窗组件挂载到Vue的原型对象上,这样每一个组件都可以通过this访问到$message,从而进行弹窗提示。
Vue.prototype.$message = Message然后根据官网给的样例,来修改我们的代码。
if (res.meta.status !== 200) return this.$message.error('账号或密码错误') this.$message.success('登陆成功')保存后运行