0
点赞
收藏
分享

微信扫一扫

用element创建vue项目(2)登录功能完善

半夜放水 2022-01-08 阅读 92

一、表单的数据绑定

1、为el-form加上:model="form"进行数据绑定。

2、为el-form里面的每一个文本输入框绑定到数据对象上具体的属性中。

<el-form :model="loginForm" label-width="0px" class="login_form">
<el-input v-model="loginForm.username" prefix-icon="iconfont icon-user"></el-input>
<el-input v-model="loginForm.password" prefix-icon="iconfont icon-3702mima"  type="password"></el-input>
<script>
export default {
    data(){
        return {
            //这是登录表单的数据绑定对象
            loginForm: {
                username: 'zs',
                password: '123'
            }
        }
    }
}
</script>

二、登录组件表单的数据验证

1、为el-form通过属性绑定指定一个rules。

<el-form :model="loginForm" :rules="loginFormRules" label-width="0px" class="login_form">

2、在data中定义这个校验对象,每个属性都是一个验证规则。

//这是表单的验证规则对象
      loginFormRules: {
                //验证用户名是否合法
                username: [],
                //验证密码是否合法
                password: []
            }

对用户名的验证规则:

{ required: true, message: '请输入登录名称', trigger: 'blur' },
{ min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }

3、为不同的表单item项通过prop来指定不同的验证规则。

<!-- 用户名 -->
<el-form-item prop="username">
<!-- 密码 -->
<el-form-item prop="password">

二、登录组件实现表单的重置

拿到表单的实例对象然后调用resetFields就能实现,这个重置方法是el-form的方法。

那么如何拿到表单的实例对象呢?

<!-- 登录表单区域 -->
<el-form ref="loginFormRef">

只需要给el-form加一个ref的引用,那么只要获取到loginFormRef,就能拿到表单的实例对象。

可以直接通过loginFormRef来调用resetFields。

为重置按钮绑定一个单击事件

<el-button type="info" @click="resetLoginForm">重置</el-button>

在js里

methods: {
    //点击重置按钮,重置登录表单
    resetLoginForm() {
        console.log(this)
    }
}

按下重置按钮,此时控制台能输出

resetLoginForm() {
            // console.log(this);
            this.$refs.loginFormRef.resetFields();
        }

 三、登陆组件登录前的预验证

给登录按钮加一个点击事件@click="login"

login() {
            this.$refs.loginFormRef.validate(valid => {
                console.log(valid);
            })
        }

四、根据预验证是否发起请求

全局导入axios,把axios这个包挂载到原型对象上

这样,每一个vue的组件都可以通过this直接访问到$http,从而发起axios请求。

import axios from 'axios'
//设置请求的根路径
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'
Vue.prototype.$http = axios
this.$refs.loginFormRef.validate(async valid => {
                // console.log(valid);
                if(!valid) return;
                const {data: res } = await this.$http.post("login", this.loginForm);
                //this.$http.post("login", this.loginForm)会输出一个Promise
                //可以在此之前加一个await来简化这个Promise
                //但是要注意await只能用在被async修饰的方法中
                console.log(res);
            })
if(res.meta.status !== 200) return console.log('登录失败');
    console.log('登录成功');

最后控制台效果:

五、登陆组件配置弹窗提示

用element ui 里面的message消息提示

首先在element.js里面导入Message组件,注意,这个组件和前几个导入的组件不一样,需要全局挂载到Vue上。这样每一个组件都可以通过this来访问到$message。

//导入弹窗提示组件
import { Message } from 'element-ui'
Vue.prototype.$message = Message

在Login.vue中修改输出

if(res.meta.status !== 200) return this.$message.error('登录失败!');;
this.$message.success('登录成功');

至此,登录功能基本实现。

举报

相关推荐

0 条评论