基于Vue3和elementplus如何实现登录功能

 6081

基于Vue3elementplus如何实现登录功能,登录页面:


基于Vue3和elementplus如何实现登录功能


注册页面:


基于Vue3和elementplus如何实现登录功能


1、引入element-plus组件库

引入组件库的方式有好多种,在这里我就在main.js全局引入了.

  1. npm i element-plus -S

main.js中代码:

  1. import { createApp } from "vue";
  2. //element-plus
  3. import ElementPlus from "element-plus";
  4. import "element-plus/dist/index.css";
  5. import App from "./App.vue";
  6. import router from "./router";
  7. import axios from "axios";
  8. import store from "./store";
  9. //创建实例
  10. const app = createApp(App);
  11. //全局应用配置
  12. app.config.globalProperties.$axios = axios;
  13.   
  14. app.use(ElementPlus).use(store).use(router).mount("#app");

引入之后自己可以用几个按钮测试一下是否引入成功.

2、登录及注册页面

html部分

views/account/Login.vue

  1. <template>
  2.   <div id="login">
  3.     <div>
  4.       <div class="form-wrap">
  5.         <ul class="menu-tab">
  6.           <li
  7.             :class="{ current: current_menu === item.type }"
  8.             v-for="item in data.tab_menu"
  9.             :key="item.type"
  10.             @click="toggleMenu(item.type)"
  11.           >
  12.             {{ item.label }}
  13.           </li>
  14.         </ul>
  15.         <el-form
  16.           :model="data.form"
  17.           ref="account_form"
  18.           :rules="data.form_rules"
  19.           label-width="80px"
  20.         >
  21.           <el-form-item prop="username">
  22.             <label class="form-label">用户名</label>
  23.             <el-input type="password" v-model="data.form.username" />
  24.           </el-form-item>
  25.           <el-form-item prop="password">
  26.             <label class="form-label">密码</label>
  27.             <el-input type="password" v-model="data.form.password" />
  28.           </el-form-item>
  29.           <el-form-item v-show="current_menu === 'register'" prop="passwords ">
  30.             <label class="form-label">确认密码</label>
  31.             <el-input type="password" v-model="data.form.passwords" />
  32.           </el-form-item>
  33.           <el-form-item prop="code">
  34.             <label class="form-label">验证码</label>
  35.             <el-row :gutter="10">
  36.               <el-col :span="14">
  37.                 <el-input v-model="data.form.code"></el-input>
  38.               </el-col>
  39.               <el-col :span="10">
  40.                 <el-button
  41.                   type="success"
  42.                   class="el-button-block"
  43.                   @click="handleGetCode"
  44.                   >获取验证码</el-button
  45.                 ></el-col
  46.               >
  47.             </el-row>
  48.           </el-form-item>
  49.           <el-form-item>
  50.             <el-button
  51.               type="danger"
  52.               class="el-button-block"
  53.               :disabled="data.submit_button_disabled"
  54.               :loading="data.submit_button_loading"
  55.               @click="submitForm"
  56.               >{{ current_menu === "login" ? "登录" : "注册" }}</el-button
  57.             >
  58.           </el-form-item>
  59.         </el-form>
  60.       </div>
  61.     </div>
  62.   </div>
  63. </template>

js部分

  1. <script>
  2. import { reactive, ref, getCurrentInstance, onBeforeUnmount } from "vue";
  3. import {
  4.   validate_email,
  5.   validate_password,
  6.   validate_code,
  7. } from "@/utils/validate";
  8. import { GetCode } from "@/api/common";
  9. import { Register, Login } from "@/api/account";
  10. import sha1 from "js-sha1"; //密码加密
  11. // ErrorHttp
  12. export default {
  13.   setup() {
  14.     const instance = getCurrentInstance();
  15.     const { proxy } = getCurrentInstance();
  16.     console.log("instance", instance);
  17.     // console.log("proxy", proxy);
  18.     // 用户名校验
  19.     const validate_name_rules = (rule, value, callback) => {
  20.       let regEmail = validate_email(value);
  21.       if (value === "") {
  22.         callback(new Error("请输入邮箱"));
  23.       } else if (!regEmail) {
  24.         callback(new Error("邮箱格式不正确"));
  25.       } else {
  26.         callback();
  27.       }
  28.     };
  29.   
  30.     //获取验证码
  31.     const handleGetCode = () => {
  32.       const username = data.form.username;
  33.       const password = data.form.password;
  34.       const passwords = data.form.passwords;
  35.       //校验用户名
  36.       if (!validate_email(username)) {
  37.         proxy.$message({
  38.           message: "用户名不能为空 或 格式不正确",
  39.           type: "error",
  40.         });
  41.         return false;
  42.       }
  43.   
  44.       //校验密码
  45.       if (!validate_password(password)) {
  46.         proxy.$message({
  47.           message: "密码不能为空 或 格式不正确",
  48.           type: "error",
  49.         });
  50.         return false;
  51.       }
  52.   
  53.       //判断为注册时,校验两次密码
  54.       if (data.current_menu === "redister" ** (password !== passwords)) {
  55.         proxy.$message({
  56.           message: "两次密码不一致",
  57.           type: "error",
  58.         });
  59.         return false;
  60.       }
  61.       //获取验证码接口
  62.       const requestData = {
  63.         username: data.form.username,
  64.         module: "register",
  65.       };
  66.   
  67.       data.code_button_loading = true;
  68.       data.code_button_text = "发送中";
  69.       GetCode(requestData)
  70.         .then((res) => {
  71.           // console.log("123", res.data);验证码
  72.           // const data=res.resCode
  73.   
  74.           const data = res;
  75.           if (data.resCode === 1024) {
  76.             proxy.$message.error(data.message);
  77.             return false;
  78.           }
  79.           // 成功 Elementui 提示
  80.           proxy.$message({
  81.             message: data.message,
  82.             type: "success",
  83.           });
  84.           //执行倒计时
  85.           countdown();
  86.         })
  87.         .catch((err) => {
  88.           console.log(err);
  89.           data.code_button_loading = false;
  90.           data.code_button_text = "发送验证码";
  91.         });
  92.   
  93.       // ErrorHttp(requestData)
  94.       //   .then((res) => {
  95.       //     console.log(res.data);
  96.       //     // const data=res.resCode
  97.       //     const data = res.data;
  98.       //     if (data.resCode === 1024) {
  99.       //       proxy.$message.error(data.message);
  100.       //       return false;
  101.       //     }
  102.       //     // 成功 Elementui 提示
  103.       //     proxy.$message({
  104.       //       message: data.message,
  105.       //       type: "success",
  106.       //     });
  107.       //     //执行倒计时
  108.       //     countdown();
  109.       //   })
  110.       //   .catch((err) => {
  111.       //     console.log(err);
  112.       //     data.code_button_loading = false;
  113.       //     data.code_button_text = "发送验证码";
  114.       //   });
  115.     };
  116.   
  117.     /** 倒计时 */
  118.     const countdown = (time) => {
  119.       if (time && typeof time !== "number") {
  120.         return false;
  121.       }
  122.       let second = time || 60; // 默认时间
  123.       data.code_button_loading = false; // 取消加载
  124.       data.code_button_disabled = true; // 禁用按钮
  125.       data.code_button_text = `倒计进${second}秒`; // 按钮文本
  126.       // 判断是否存在定时器,存在则先清除
  127.       if (data.code_button_timer) {
  128.         clearInterval(data.code_button_timer);
  129.       }
  130.       // 开启定时器
  131.       data.code_button_timer = setInterval(() => {
  132.         second--;
  133.         data.code_button_text = `倒计进${second}秒`; // 按钮文本
  134.         if (second <= 0) {
  135.           data.code_button_text = `重新获取`; // 按钮文本
  136.           data.code_button_disabled = false; // 启用按钮
  137.           clearInterval(data.code_button_timer); // 清除倒计时
  138.         }
  139.       }, 1000);
  140.     };
  141.   
  142.     // 组件销毁之前 - 生命周期
  143.     onBeforeUnmount(() => {
  144.       clearInterval(data.code_button_timer); // 清除倒计时
  145.     });
  146.   
  147.     // 校验确认密码
  148.     const validate_password_rules = (rule, value, callback) => {
  149.       let regPassword = validate_password(value);
  150.       if (value === "") {
  151.         callback(new Error("请输入密码"));
  152.       } else if (!regPassword) {
  153.         callback(new Error("请输入>=6并且<=20位的密码,包含数字、字母"));
  154.       } else {
  155.         callback();
  156.       }
  157.     };
  158.   
  159.     // 校验确认密码
  160.     const validate_passwords_rules = (rule, value, callback) => {
  161.       // 如果是登录,不需要校验确认密码,默认通过
  162.       if (data.current_menu === "login") {
  163.         callback();
  164.       }
  165.       let regPassword = validate_password(value);
  166.       // 获取“密码”
  167.       const passwordValue = data.form.password;
  168.       if (value === "") {
  169.         callback(new Error("请输入密码"));
  170.       } else if (!regPassword) {
  171.         callback(new Error("请输入>=6并且<=20位的密码,包含数字、字母"));
  172.       } else if (passwordValue && passwordValue !== value) {
  173.         callback(new Error("两次密码不一致"));
  174.       } else {
  175.         callback();
  176.       }
  177.     };
  178.   
  179.     const validate_code_rules = (rule, value, callback) => {
  180.       let regCode = validate_code(value);
  181.       // 激活提交按钮
  182.       data.submit_button_disabled = false;
  183.       if (value === "") {
  184.         callback(new Error("请输入验证码"));
  185.       } else if (!regCode) {
  186.         callback(new Error("请输入6位的验证码"));
  187.       } else {
  188.         callback();
  189.       }
  190.     };
  191.   
  192.     // 提交表单
  193.     const submitForm = () => {
  194.       // let res = proxy.$refs.account_form;
  195.       proxy.$refs.account_form.validate((valid) => {
  196.         if (valid) {
  197.           console.log("提交表单", current_menu.value);
  198.           current_menu.value === "login" ? login() : register();
  199.           // register();
  200.         } else {
  201.           alert("error submit!");
  202.           return false;
  203.         }
  204.       });
  205.       // console.log(" 提交表单", res);
  206.     };
  207.     /** 登录 */
  208.     const login = () => {
  209.       const requestData = {
  210.         username: data.form.username,
  211.         password: sha1(data.form.password),
  212.         code: data.form.code,
  213.       };
  214.       data.submit_button_loading = true;
  215.       Login(requestData)
  216.         .then((response) => {
  217.           console.log("login", response);
  218.           data.submit_button_loading = false;
  219.           proxy.$message({
  220.             message: response.message,
  221.             type: "success",
  222.           });
  223.   
  224.           reset();
  225.         })
  226.         .catch((error) => {
  227.           console.log("登录失败", error);
  228.           data.submit_button_loading = false;
  229.         });
  230.     };
  231.     //注册
  232.     const register = () => {
  233.       const requestData = {
  234.         username: data.form.username,
  235.         password: sha1(data.form.password),
  236.         code: data.form.code,
  237.       };
  238.       data.submit_button_loading = true;
  239.       Register(requestData)
  240.         .then((res) => {
  241.           proxy.$message({
  242.             message: res.message,
  243.             type: "success",
  244.           });
  245.         })
  246.         .catch((error) => {
  247.           console.log("注册错误", error);
  248.           data.submit_button_loading = false;
  249.         });
  250.     };
  251.   
  252.     /** 重置 */
  253.     const reset = () => {
  254.       // 重置表单
  255.       proxy.$refs.form.resetFields();
  256.       // 切回登录模式
  257.       data.current_menu = "login";
  258.       // 清除定时器
  259.       data.code_button_timer && clearInterval(data.code_button_timer);
  260.       // 获取验证码重置文本
  261.       data.code_button_text = "获取验证码";
  262.       // 获取验证码激活
  263.       data.code_button_disabled = false;
  264.       // 禁用提交按钮
  265.       data.submit_button_disabled = true;
  266.       // 取消提交按钮加载
  267.       data.submit_button_loading = false;
  268.     };
  269.   
  270.     const data = reactive({
  271.       form_rules: {
  272.         username: [{ validator: validate_name_rules, trigger: "change" }],
  273.         password: [{ validator: validate_password_rules, trigger: "change" }],
  274.         passwords: [{ validator: validate_passwords_rules, trigger: "change" }],
  275.         code: [{ validator: validate_code_rules, trigger: "change" }],
  276.       },
  277.       form: {
  278.         username: "", // 用户名
  279.         password: "", // 密码
  280.         passwords: "", // 确认密码
  281.         code: "", // 验证码
  282.       },
  283.       tab_menu: [
  284.         { type: "login", label: "登录" },
  285.         { type: "register", label: "注册" },
  286.       ],
  287.       /**
  288.        * 获取验证码按钮交互
  289.        */
  290.       code_button_disabled: false,
  291.       code_button_loading: false,
  292.       code_button_text: "获取验证码",
  293.       code_button_timer: null,
  294.       // 提交按钮
  295.       submit_button_disabled: true,
  296.     });
  297.   
  298.     const toggleMenu = (type) => {
  299.       current_menu.value = type;
  300.     };
  301.     let current_menu = ref(data.tab_menu[0].type);
  302.     // const dataItem = toRefs(data);
  303.     return {
  304.       // ...dataItem,
  305.       data,
  306.       current_menu,
  307.       toggleMenu,
  308.       handleGetCode,
  309.       submitForm,
  310.       register,
  311.       reset,
  312.       login,
  313.     };
  314.   },
  315. };
  316. </script>

css部分(使用了scss)

  1. <style scoped>
  2. #login {
  3.   height: 100vh;
  4.   background-color: #344a5f;
  5. }
  6. .form-wrap {
  7.   width: 320px;
  8.   padding-top: 100px;
  9.   margin: auto;
  10. }
  11. .menu-tab {
  12.   text-align: center;
  13.   li {
  14.     display: inline-block;
  15.     padding: 10px 24px;
  16.     margin: 0 10px;
  17.     color: #fff;
  18.     font-size: 14px;
  19.     border-radius: 5px;
  20.     cursor: pointer;
  21.     &.current {
  22.       background-color: rgba(0, 0, 0, 0.1);
  23.     }
  24.   }
  25. }
  26. .form-label {
  27.   display: block;
  28.   color: #fff;
  29.   font-size: 14px;
  30. }
  31. </style>


3、封装一些公共方法及样式

新建styles文件夹,然后新建几个样式文件:

normalize.scss

  1. /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */
  2.   
  3. /* Document
  4.    ========================================================================== */
  5.   
  6. /**
  7.  * 1. Correct the line height in all browsers.
  8.  * 2. Prevent adjustments of font size after orientation changes in iOS.
  9.  */
  10. /* div的默认样式不存在padding和margin为0的情况*/
  11. html, body, span, applet, object, iframe,
  12. h2, h3, h4, h5, h6, h7, p, blockquote, pre,
  13. a, abbr, acronym, address, big, cite, code,
  14. del, dfn, em, img, ins, kbd, q, s, samp,
  15. small, strike, strong, sub, sup, tt, var,
  16. b, u, i, center,
  17. dl, dt, dd, ol, ul,
  18. fieldset, form, legend,
  19. table, caption, tbody, tfoot, thead, tr, th, td,
  20. article, aside, canvas, details, embed, 
  21. figure, figcaption, footer, header, hgroup, 
  22. menu, nav, output, ruby, section, summary,
  23. time, mark, audio, video {
  24.   margin: 0;
  25.   padding: 0;
  26.   font-size: 100%;
  27.   font: inherit;
  28.   vertical-align: baseline;
  29. }
  30. /* HTML5 display-role reset for older browsers */
  31. article, aside, details, figcaption, figure, 
  32. footer, header, hgroup, menu, nav, section {
  33.   display: block;
  34. }
  35. html {
  36.   line-height: 1.15; /* 1 */
  37.   -webkit-text-size-adjust: 100%; /* 2 */
  38. }
  39.  
  40. /* Sections
  41.    ========================================================================== */
  42.  
  43. /**
  44.  * Remove the margin in all browsers.
  45.  */
  46.  
  47. body {
  48.   margin: 0;
  49.   font-family: 'Microsoft YaHei';
  50.   font-size: 14px;
  51. }
  52.  
  53. /**
  54.  * Render the `main` element consistently in IE.
  55.  */
  56.  
  57. main {
  58.   display: block;
  59. }
  60.  
  61. /**
  62.  * Correct the font size and margin on `h2` elements within `section` and
  63.  * `article` contexts in Chrome, Firefox, and Safari.
  64.  */
  65.  
  66.  
  67. /* Grouping content
  68.    ========================================================================== */
  69.  
  70. /**
  71.  * 1. Add the correct box sizing in Firefox.
  72.  * 2. Show the overflow in Edge and IE.
  73.  */
  74.  
  75. hr {
  76.   box-sizing: content-box; /* 1 */
  77.   height: 0; /* 1 */
  78.   overflow: visible; /* 2 */
  79. }
  80.  
  81. /**
  82.  * 1. Correct the inheritance and scaling of font size in all browsers.
  83.  * 2. Correct the odd `em` font sizing in all browsers.
  84.  */
  85.  
  86. pre {
  87.   font-family: monospace, monospace; /* 1 */
  88.   font-size: 1em; /* 2 */
  89. }
  90.  
  91. /* Text-level semantics
  92.    ========================================================================== */
  93.  
  94. /**
  95.  * Remove the gray background on active links in IE 10.
  96.  */
  97.  
  98. {
  99.   background-color: transparent;
  100.   text-decoration: none;
  101. }
  102.  
  103. /**
  104.  * 1. Remove the bottom border in Chrome 57-
  105.  * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
  106.  */
  107.  
  108. abbr[title] {
  109.   border-bottom: none; /* 1 */
  110.   text-decoration: underline; /* 2 */
  111.   text-decoration: underline dotted; /* 2 */
  112. }
  113.  
  114. /**
  115.  * Add the correct font weight in Chrome, Edge, and Safari.
  116.  */
  117.  
  118. b,
  119. strong {
  120.   font-weight: bolder;
  121. }
  122.  
  123. /**
  124.  * 1. Correct the inheritance and scaling of font size in all browsers.
  125.  * 2. Correct the odd `em` font sizing in all browsers.
  126.  */
  127.  
  128. code,
  129. kbd,
  130. samp {
  131.   font-family: monospace, monospace; /* 1 */
  132.   font-size: 1em; /* 2 */
  133. }
  134.  
  135. /**
  136.  * Add the correct font size in all browsers.
  137.  */
  138.  
  139. small {
  140.   font-size: 80%;
  141. }
  142.  
  143. /**
  144.  * Prevent `sub` and `sup` elements from affecting the line height in
  145.  * all browsers.
  146.  */
  147.  
  148. sub,
  149. sup {
  150.   font-size: 75%;
  151.   line-height: 0;
  152.   position: relative;
  153.   vertical-align: baseline;
  154. }
  155.  
  156. sub {
  157.   bottom: -0.25em;
  158. }
  159.  
  160. sup {
  161.   top: -0.5em;
  162. }
  163.  
  164. /* Embedded content
  165.    ========================================================================== */
  166.  
  167. /**
  168.  * Remove the border on images inside links in IE 10.
  169.  */
  170.  
  171. img {
  172.   display: block;
  173.   border-style: none;
  174. }
  175.  
  176. /* Forms
  177.    ========================================================================== */
  178.  
  179. /**
  180.  * 1. Change the font styles in all browsers.
  181.  * 2. Remove the margin in Firefox and Safari.
  182.  */
  183.  
  184. button,
  185. input,
  186. optgroup,
  187. select,
  188. textarea {
  189.   font-family: inherit; /* 1 */
  190.   font-size: 100%; /* 1 */
  191.   margin: 0; /* 2 */
  192. }
  193.  
  194. /**
  195.  * Show the overflow in IE.
  196.  * 1. Show the overflow in Edge.
  197.  */
  198.  
  199. button,
  200. input { /* 1 */
  201.   overflow: visible;
  202. }
  203.  
  204. /**
  205.  * Remove the inheritance of text transform in Edge, Firefox, and IE.
  206.  * 1. Remove the inheritance of text transform in Firefox.
  207.  */
  208.  
  209. button,
  210. select { /* 1 */
  211.   text-transform: none;
  212. }
  213.  
  214. /**
  215.  * Correct the inability to style clickable types in iOS and Safari.
  216.  */
  217.  
  218. button,
  219. [type="button"],
  220. [type="reset"],
  221. [type="submit"] {
  222.   -webkit-appearance: button;
  223. }
  224.  
  225. /**
  226.  * Remove the inner border and padding in Firefox.
  227.  */
  228.  
  229. button::-moz-focus-inner,
  230. [type="button"]::-moz-focus-inner,
  231. [type="reset"]::-moz-focus-inner,
  232. [type="submit"]::-moz-focus-inner {
  233.   border-style: none;
  234.   padding: 0;
  235. }
  236.  
  237. /**
  238.  * Restore the focus styles unset by the previous rule.
  239.  */
  240.  
  241. button:-moz-focusring,
  242. [type="button"]:-moz-focusring,
  243. [type="reset"]:-moz-focusring,
  244. [type="submit"]:-moz-focusring {
  245.   outline: 1px dotted ButtonText;
  246. }
  247.  
  248. /**
  249.  * Correct the padding in Firefox.
  250.  */
  251.  
  252. fieldset {
  253.   padding: 0.35em 0.75em 0.625em;
  254. }
  255.  
  256. /**
  257.  * 1. Correct the text wrapping in Edge and IE.
  258.  * 2. Correct the color inheritance from `fieldset` elements in IE.
  259.  * 3. Remove the padding so developers are not caught out when they zero out
  260.  *    `fieldset` elements in all browsers.
  261.  */
  262.  
  263. legend {
  264.   box-sizing: border-box; /* 1 */
  265.   color: inherit; /* 2 */
  266.   display: table; /* 1 */
  267.   max-width: 100%; /* 1 */
  268.   padding: 0; /* 3 */
  269.   white-space: normal; /* 1 */
  270. }
  271.  
  272. /**
  273.  * Add the correct vertical alignment in Chrome, Firefox, and Opera.
  274.  */
  275.  
  276. progress {
  277.   vertical-align: baseline;
  278. }
  279.  
  280. /**
  281.  * Remove the default vertical scrollbar in IE 10+.
  282.  */
  283.  
  284. textarea {
  285.   overflow: auto;
  286. }
  287.  
  288. /**
  289.  * 1. Add the correct box sizing in IE 10.
  290.  * 2. Remove the padding in IE 10.
  291.  */
  292.  
  293. [type="checkbox"],
  294. [type="radio"] {
  295.   box-sizing: border-box; /* 1 */
  296.   padding: 0; /* 2 */
  297. }
  298.  
  299. /**
  300.  * Correct the cursor style of increment and decrement buttons in Chrome.
  301.  */
  302.  
  303. [type="number"]::-webkit-inner-spin-button,
  304. [type="number"]::-webkit-outer-spin-button {
  305.   height: auto;
  306. }
  307.  
  308. /**
  309.  * 1. Correct the odd appearance in Chrome and Safari.
  310.  * 2. Correct the outline style in Safari.
  311.  */
  312.  
  313. [type="search"] {
  314.   -webkit-appearance: textfield; /* 1 */
  315.   outline-offset: -2px; /* 2 */
  316. }
  317.  
  318. /**
  319.  * Remove the inner padding in Chrome and Safari on macOS.
  320.  */
  321.  
  322. [type="search"]::-webkit-search-decoration {
  323.   -webkit-appearance: none;
  324. }
  325.  
  326. /**
  327.  * 1. Correct the inability to style clickable types in iOS and Safari.
  328.  * 2. Change font properties to `inherit` in Safari.
  329.  */
  330.  
  331. ::-webkit-file-upload-button {
  332.   -webkit-appearance: button; /* 1 */
  333.   font: inherit; /* 2 */
  334. }
  335.  
  336. /* Interactive
  337.    ========================================================================== */
  338.  
  339. /*
  340.  * Add the correct display in Edge, IE 10+, and Firefox.
  341.  */
  342.  
  343. details {
  344.   display: block;
  345. }
  346.  
  347. /*
  348.  * Add the correct display in all browsers.
  349.  */
  350.  
  351. summary {
  352.   display: list-item;
  353. }
  354.  
  355. /* Misc
  356.    ========================================================================== */
  357.  
  358. /**
  359.  * Add the correct display in IE 10+.
  360.  */
  361.  
  362. template {
  363.   display: none;
  364. }
  365.  
  366. /**
  367.  * Add the correct display in IE 10.
  368.  */
  369.  
  370. [hidden] {
  371.   display: none;
  372. }
  373. ul, li { list-style: none; }

elementui.scss(当时测试时用的)

  1. .el-button-block{
  2.     display: block;
  3.     width: 100%;
  4. }

新建main.scss(引入上方两个样式文件)

  1. @import "./normalize.scss";
  2. @import './elementui.scss'

vue.config.js配置一下样式文件

  1. css: {
  2.   // 是否使用css分离插件 ExtractTextPlugin
  3.   extract: true,
  4.   // 开启 CSS source maps?
  5.   sourceMap: false,
  6.   // css预设器配置项
  7.   loaderOptions: {
  8.     scss: {
  9.       additionalData: `@import "./src/styles/main.scss";`,
  10.     },
  11.   },
  12.   // requireModuleExtension: true,
  13. },

登录中封装的校验方法

新建utils文件夹,a.validate.js

  1. // 校验邮箱
  2. export function validate_email(value) {
  3.   let regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
  4.   return regEmail.test(value);
  5. }
  6.   
  7. // 校验密码
  8. export function validate_password(value) {
  9.   let regPassword = /^(?!\D+$)(?![^a-zA-Z]+$)\S{6,20}$/;
  10.   return regPassword.test(value);
  11. }
  12.   
  13. // 校验验证码
  14. export function validate_code(value) {
  15.   let regCode = /^[a-z0-9]{6}$/;
  16.   return regCode.test(value);
  17. }

封装请求方法

  1. npm i axios -S

记得先在main.js中引入axios

  1. import axios from "axios";

utils中新建request.js

  1. import axios from "axios";
  2. //引入element-plus
  3. import { ElMessage } from "element-plus";
  4. console.log("11", process.env.VUE_APP_API); //undefined??
  5.   
  6. //创建实例
  7. const service = axios.create({
  8.   baseURL: "/devApi", //请求地址
  9.   timeout: 5000, //超时
  10. });
  11.   
  12. //添加请求拦截器
  13. service.interceptors.request.use(
  14.   function (config) {
  15.     //在发送请求之前做些什么
  16.     return config;
  17.   },
  18.   function (error) {
  19.     console.log(error.request);
  20.     const errorData = JSON.parse(error.request.response);
  21.     if (errorData.message) {
  22.       //判断是否具有message属性
  23.       ElMessage({
  24.         message: errorData.message,
  25.         type: "error",
  26.       });
  27.     }
  28.     //对请求错误做些什么
  29.     return Promise.reject(errorData);
  30.   }
  31. );
  32.   
  33. //添加响  应拦截器
  34. service.interceptors.response.use(
  35.   function (response) {
  36.     //对响应数据做些什么
  37.     console.log("响应数据", response);
  38.     const data = response.data;
  39.     if (data.resCode === 0) {
  40.       return Promise.resolve(data);
  41.     } else {
  42.       ElMessage({
  43.         message: data.message,
  44.         type: "error",
  45.       });
  46.       return Promise.reject(data);
  47.     }
  48.   },
  49.   function (error) {
  50.     //对响应错误做些什么
  51.     const errorData = JSON.parse(error.request.response);
  52.     if (errorData.message) {
  53.       //判断是否具有message属性
  54.       ElMessage({
  55.         message: errorData.message,
  56.         type: "error",
  57.       });
  58.     }
  59.   
  60.     return Promise.reject(errorData);
  61.   }
  62. );
  63.   
  64. //暴露service
  65. export default service;


4、配置环境变量

和项目根路径同级,新建几个文件:.env.development

  1. VUE_APP_API = '/devApi'

可以自定义,但是必须是VUE_APP_XXX的格式

.env.production

  1. VUE_APP_API = '/production'

.env.test

  1. VUE_APP_API = '/test'

配置完后记得在axios文件中打印一下,看下能输出自己配置的环境变量吗。


基于Vue3和elementplus如何实现登录功能


5、配置代理(跨域)

基本大同小异,代理地址改成自己的就可以了.

  1. devServer: {
  2.   open: false, //编译完成是否自动打开网页
  3.   host: "0.0.0.0", //指定使用地址,默认是localhost,0.0.0.0代表可以被外界访问
  4.   port: 8080,
  5.   proxy: {
  6.     "/devApi": {
  7.       target: "http://v3.web-jshtml.cn/api", //(必选)API服务器的地址
  8.       changeOrigin: true, //(必选) 是否允许跨域
  9.       ws: false, //(可选) 是否启用websockets
  10.       secure: false, //(可选) 是否启用https接口
  11.       pathRewrite: {
  12.         "^/devApi": "", //匹配开头为/devApi的字符串,并替换成空字符串
  13.       },
  14.     },
  15.   },
  16. },


本文网址:https://www.zztuku.com/index.php/detail-14175.html
站长图库 - 基于Vue3和elementplus如何实现登录功能
申明:本文转载于《CSDN》,如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐