<style scoped>
#page-login {
    width: 500px;
    margin: 200px auto 0;
}
</style>
<template>
    <div id="page-login">
        <el-form
            ref="form"
            :model="loginForm"
            :rules="rules"
            status-icon
            label-width="120px"
            class="demo-ruleForm"
        >
            <el-form-item label="" prop="username">
                <el-input v-model="loginForm.username" placeholder="用户名" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="" prop="password">
                <el-input v-model="loginForm.password" placeholder="登录密码" type="password" autocomplete="off"/>
            </el-form-item>
            <el-form-item>
                <el-button style="width: 100%" type="primary" @click="submitForm">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import {defineComponent, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {useRouter} from 'vue-router'

export default defineComponent({
    name: 'Login',
    method:{
        gotoMain(){
            this.$router.push('/');
        }
    },
    setup() {
        /**
         *
         * @type {Ref<FormInstance>}
         */
        const form = ref(null);
        // 使用reactive将对象转换成响应对象
        const loginForm = reactive({
            password: '',
            username: ''
        })
        const checkPassword = (rule, value, callback) => {
            if (!value) callback(Error('请填写密码')) // 验证不通过
            else callback() // 验证通过
        }
        const rules = reactive({
            username: [
                {required: true, message: '请填写用户名称', trigger: 'blur'}
            ],
            password: [
                {validator: checkPassword, trigger: 'blur'}
            ]
        })
        const router = useRouter(); // 获取路由对象
        const submitForm = () => {
            form.value.validate((isValid) => {
                if (isValid) {
                    ElMessage.success('登录成功')
                    router.replace('/')
                } else {
                    ElMessage.info('验证不通过')
                }
            })
        };
        return {
            loginForm, submitForm, rules, form
        }
    }
})
</script>
