经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Vue.js » 查看文章
基于Vue3和element-plus实现登录功能(最终完整版)
来源:jb51  时间:2023/3/8 10:59:04  对本文有异议

先看一下最终要实现的效果:

登录页面:

注册页面:

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

css部分(使用了scss)

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

封装请求方法

  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. const service = axios.create({
  7. baseURL: "/devApi", //请求地址
  8. timeout: 5000, //超时
  9. });
  10. //添加请求拦截器
  11. service.interceptors.request.use(
  12. function (config) {
  13. //在发送请求之前做些什么
  14. return config;
  15. },
  16. function (error) {
  17. console.log(error.request);
  18. const errorData = JSON.parse(error.request.response);
  19. if (errorData.message) {
  20. //判断是否具有message属性
  21. ElMessage({
  22. message: errorData.message,
  23. type: "error",
  24. });
  25. }
  26. //对请求错误做些什么
  27. return Promise.reject(errorData);
  28. }
  29. );
  30. //添加响 应拦截器
  31. service.interceptors.response.use(
  32. function (response) {
  33. //对响应数据做些什么
  34. console.log("响应数据", response);
  35. const data = response.data;
  36. if (data.resCode === 0) {
  37. return Promise.resolve(data);
  38. } else {
  39. ElMessage({
  40. message: data.message,
  41. type: "error",
  42. });
  43. return Promise.reject(data);
  44. }
  45. },
  46. function (error) {
  47. //对响应错误做些什么
  48. const errorData = JSON.parse(error.request.response);
  49. if (errorData.message) {
  50. //判断是否具有message属性
  51. ElMessage({
  52. message: errorData.message,
  53. type: "error",
  54. });
  55. }
  56. return Promise.reject(errorData);
  57. }
  58. );
  59. //暴露service
  60. 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文件中打印一下,看下能输出自己配置的环境变量吗.

(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. },

登录基本上是完成了,还有优化的点,比如说登录放在vuex中,这个我先不实现了,各位小伙伴觉得还不错的话,动手点个赞喽!!!

到此这篇关于基于Vue3和element-plus实现一个完整的登录功能的文章就介绍到这了,更多相关vue3 element-plus登录内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号