vue3-实现登录页面

318 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第23天,点击查看活动详情

首先先搞一个div当容器,先搞一个背景图片

  <div class="box">

  </div>

写点css样式

.box{
  width: 100%;
  height: 100%;
  padding-top:1px;
  background: url(https://img0.baidu.com/it/u=1474625213,1040099858&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1671037200&t=3d60740a09517d6f484ce46729b1c667) ;
  background-size: 100% 100%;
}

然后页面上就有一个图片了

image.png

然后再加个div,当成表单的盒子,然后从element-plus官网,复制一下自定义校验那个例子,模版结构大概就是这个样式,然后先把使用的数据准备一下,

  <div class="container">
      <el-form
        ref="ruleFormRef"
        :model="userForm"
        status-icon
        label-width="120px"
        :rules="rules"
        class="demo-ruleForm"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="userForm.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button class="form_btn" type="primary" @click="submitForm(ruleFormRef)"
            >登录</el-button
          >
          <el-button  class="form_btn"  @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

scripte lang为ts,然后导入defineComponent方法,这个方法接收vue的配置,然后让这些配置有ts提示,导入reactive方法,创建响应式对象常用的方法,toRefs把响应式对象安全的解构成响应式的数据,如果直接解构,不使用这个方法,解构的对象就失去了响应式的能力,然后配置项里配置setup函数,使用reactive定义响应式的userForm和rules,然后搞两个方法,直接return出去,此时模版里可以直接访问的变量有userForm,rules,submitForm,resetForm等

<script lang="ts">
import { defineComponent, reactive, toRefs } from "vue";

export default defineComponent({
  setup() {
    const data = reactive({
      userForm: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    });
    function submitForm(ref: any) {
      console.log(ref);
    }
    function resetForm(ref: any) {
      console.log(ref);
    }
    return { ...toRefs(data), submitForm, resetForm };
  },
});
</script>

写点css美化一下

<style lang="scss" scoped>
.container {
  width: 500px;
  margin: 200px auto;
  padding: 40px 80px 40px 0px;
  background-color: #fff;
  border-radius: 10px;
  .form_btn{
    width: 48%;
  }
}
.box{
  width: 100%;
  height: 100%;
  padding-top:1px;
  background: url(https://img0.baidu.com/it/u=1474625213,1040099858&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1671037200&t=3d60740a09517d6f484ce46729b1c667) ;
  background-size: 100% 100%;
}
</style>

效果直接拉满,跟一些小网站的登录页面一模一样了

image.png