index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import {
  2. createRouter,
  3. createWebHistory,
  4. createWebHashHistory,
  5. } from "vue-router";
  6. import routes from "./routes";
  7. import LibForWeixin from "@/utils/LibForWeixin";
  8. import { useUserStore, useAppStore } from "@/store";
  9. import { getUrlParam } from "../utils";
  10. const router = createRouter({
  11. // history: createWebHistory(import.meta.env.VITE_BASE),
  12. history: createWebHashHistory(),
  13. routes,
  14. scrollBehavior: () => ({
  15. el: "#app",
  16. top: 0,
  17. behavior: "smooth",
  18. }),
  19. });
  20. let pattern =
  21. /^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/;
  22. const whiteList = ["Login", "WxLogin"];
  23. router.beforeEach(async (to, from, next) => {
  24. console.log("to:", to);
  25. const code = getUrlParam("code");
  26. const appStore = useAppStore();
  27. const userStore = useUserStore();
  28. if (
  29. !userStore.openId &&
  30. !code &&
  31. !import.meta.env.VITE_NOT_NEED_WX_AUTH
  32. // &&!(
  33. // pattern.test(location.hostname) ||
  34. // location.hostname === "apply-test.qmth.com.cn"
  35. // )
  36. ) {
  37. LibForWeixin.auth();
  38. return;
  39. }
  40. if (
  41. !appStore.globalConfig &&
  42. to.name !== "WxLogin" &&
  43. (userStore.openId ||
  44. pattern.test(location.hostname) ||
  45. location.hostname === "apply-test.qmth.com.cn")
  46. ) {
  47. let config = await appStore.getGlobalConfig();
  48. if (((config && !config?.taskTitle) || !config) && to.name !== "Login") {
  49. next({ name: "Login", replace: true });
  50. return;
  51. }
  52. }
  53. if (to.meta.jsApiList) {
  54. await LibForWeixin.initJSSDK(to.meta.jsApiList)
  55. .then(() => {
  56. console.log("config JS-SDK success");
  57. })
  58. .catch(() => {
  59. console.log("config JS-SDK fail");
  60. });
  61. }
  62. if (whiteList.includes(to.name)) {
  63. next();
  64. return;
  65. }
  66. if (!userStore.loginInfo) {
  67. next({ name: "Login", replace: true });
  68. } else {
  69. next();
  70. }
  71. });
  72. router.afterEach((to) => {
  73. if (to.path !== "/favicon.icon") {
  74. document.title = to.meta.title ? to.meta.title : "";
  75. }
  76. window.scrollTo(0, 0);
  77. });
  78. export default router;