Explorar o código

feat: 优化params参数

bill hai 3 meses
pai
achega
2b3371317f

+ 67 - 4
src/example/env.ts

@@ -1,8 +1,71 @@
-const urlParams = new URLSearchParams(location.search);
+import { inRevise } from "@/utils/shared";
+import { computed, ref, watch } from "vue";
 
-export const params: Record<string, string> = {};
 
-for (const [name, value] of urlParams.entries()) {
-  (params as any)[name] = value
+export const urlUpdateQuery = (link: string, params: Record<string, string>, rep = false) => {
+  const url = new URL(link)
+  const ndx = url.hash.indexOf('?')
+  let search: URLSearchParams
+  if (!rep && ~ndx) {
+    search = new URLSearchParams({
+      ...(urlGetQuery(link) as any),
+      ...params
+    })
+    for (const key in params) {
+      search.set(key, params[key])
+    }
+  } else {
+    search = new URLSearchParams(params)
+  }
+  url.hash = url.hash.substring(0, ndx + 1) + search.toString()
+
+  return url.toString()
+}
+
+export const urlGetQuery = (link: string) => {
+  const url = new URL(link)
+  const hash = url.hash
+  const ndx = hash.indexOf('?')
+  if (!~ndx) return {}
+
+  const sParams = new URLSearchParams(hash.substring(ndx));
+  const rParams: Record<string, string> = {};
+  [...sParams.entries()].forEach(item => {
+    rParams[item[0]] = item[1]
+  })
+  return rParams
+}
+
+export const params = ref<Record<string, string | undefined>>({})
+const updateParams = () => {
+  const rParams = urlGetQuery(location.href)
+  if (inRevise(rParams, params.value)) {
+    params.value = rParams
+  }
 }
 
+watch(params, () => {
+  const sParams = new URLSearchParams();
+  for (const key in params.value) {
+    params.value[key] && sParams.append(key, params.value[key])
+  }
+  const ndx = location.hash.indexOf('?')
+  location.replace(location.hash.substring(0, ~ndx ? ndx : undefined) + '?' + sParams.toString())
+}, {deep: true})
+
+
+updateParams()
+window.addEventListener('hashchange', updateParams)
+
+const getQuisk = (key: string) => computed({
+  get() {
+    return params.value[key]
+  },
+  set(val: string) {
+    params.value[key] = val
+  }
+})
+
+export const tabulationId = getQuisk('tabulationId')
+export const overviewId = getQuisk('overviewId')
+export const token = getQuisk('token')

+ 37 - 30
src/example/fuse/enter.ts

@@ -1,7 +1,7 @@
 import type { TabCover } from "./store";
 import type { Scene } from "../../example/platform/platform-resource";
 import type { StoreData } from "@/core/store/store";
-import { params } from "../env";
+import { token, params, urlUpdateQuery, urlGetQuery } from "../env";
 import { genLoading } from "../loadding";
 import { tempStrFill } from "@/utils/shared";
 
@@ -24,22 +24,29 @@ const viewURLS = {
   [SCENE_TYPE.fuse]: import.meta.env.VITE_FUSE_VIEW,
 };
 
-const token = (params.token || localStorage.getItem("token")) as string;
-const headers = { token, caseId: params.caseId, 'page-type': 'edit' } 
+const getHeaders = () => ({
+  token: token.value || localStorage.getItem("token") || "",
+  caseId: params.value.caseId || "",
+  "page-type": "edit",
+});
 const get = (url: string, params: Record<string, any>) => {
   const p = new URLSearchParams();
   for (const key in params) {
     p.append(key, params[key]);
   }
   const l = `${resourceURLS[SCENE_TYPE.fuse]}${url}?${p.toString()}`;
-  return after(fetch(l, { method: "get", headers} ));
+  return after(fetch(l, { method: "get", headers: getHeaders() }));
 };
 
 const post = (url: string, data: Record<string, any>) => {
   const l = `${resourceURLS[SCENE_TYPE.fuse]}${url}`;
+  console.log(data)
   return after(
     fetch(l, {
-      headers: { "Content-Type": "application/json;charset=UTF-8", ...headers },
+      headers: {
+        "Content-Type": "application/json;charset=UTF-8",
+        ...getHeaders(),
+      },
       method: "post",
       body: JSON.stringify(data),
     })
@@ -55,7 +62,7 @@ const postFile = (url: string, data: Record<string, any>) => {
   const l = `${resourceURLS[SCENE_TYPE.fuse]}${url}`;
   return after(
     fetch(l, {
-      headers,
+      headers: getHeaders(),
       method: "post",
       body: formData,
     })
@@ -64,27 +71,28 @@ const postFile = (url: string, data: Record<string, any>) => {
 
 const login = (isBack = true) => {
   if (import.meta.env.VITE_LOGIN_VIEW) {
-    const curUrl = new URL(location.href)
-    curUrl.searchParams.delete('token')
-
-    const link = isBack
-      ? tempStrFill(import.meta.env.VITE_LOGIN_VIEW, {
-          redirect: escape(curUrl.toString()),
-        })
-      : import.meta.env.VITE_LOGIN_VIEW;
-    const url = new URL(link)
+    const p: any = { ...params.value };
+    delete p.token;
+
+    const cur = urlUpdateQuery(location.href, p, true);
+    let link = tempStrFill(import.meta.env.VITE_LOGIN_VIEW, { redirect: escape(cur) })
+    
     if (!isBack) {
-      url.searchParams.delete('redirect')
+      const url = new URL(link);
+      url.searchParams.delete("redirect");
+      const query = urlGetQuery(url.toString())
+      delete query['redirect']
+      link = urlUpdateQuery(url.toString(), query, true)
     }
-    location.replace(url.toString());
+    location.replace(link);
   }
 };
 
 const after = async (fet: Promise<Response>) => {
   const res = await fet.then((res) => res.json());
-  if ([4008, 4010].includes(res.code)) {
+  if ([4008, 4010, 7012].includes(res.code)) {
     setTimeout(() => {
-      login();
+      login(res.code !== 7012);
     }, 1000);
     throw res.message;
   } else if (res.code !== 0) {
@@ -94,13 +102,13 @@ const after = async (fet: Promise<Response>) => {
   }
 };
 
-if (!params.caseId || !token) {
-  login(!!params.caseId);
+if (!params.value.caseId || !token) {
+  login(!!params.value.caseId);
 }
 
 const getSceneList = genLoading(async (keyword: string): Promise<Scene[]> => {
   const list = await post(`fusion/case/sceneListPost`, {
-    caseId: params.caseId,
+    caseId: params.value.caseId,
     isMesh: 1,
     sceneName: keyword,
   });
@@ -109,7 +117,7 @@ const getSceneList = genLoading(async (keyword: string): Promise<Scene[]> => {
     m: item.num,
     title: item.name,
     id: item.id.toString(),
-    token
+    token,
   }));
 });
 
@@ -136,7 +144,7 @@ const saveOverviewData = genLoading(
     }
   ) => {
     const item = await post(`fusion/caseOverview/addOrUpdate`, {
-      ...params,
+      ...params.value,
       id,
       store: JSON.stringify(data.store),
       viewport: JSON.stringify(data.viewport),
@@ -149,7 +157,6 @@ const getTabulationId = async (id: string) => {
   const list = await get("fusion/caseTabulation/getByOverviewId", {
     overviewId: id,
   });
-  console.log(list)
   return list[0]?.id;
 };
 
@@ -186,7 +193,7 @@ const saveTabulationData = genLoading(
     }
   ) => {
     const item = await post("fusion/caseTabulation/addOrUpdate", {
-      ...params,
+      ...params.value,
       id,
       store: JSON.stringify(data.store),
       viewport: JSON.stringify(data.viewport),
@@ -201,13 +208,13 @@ const saveTabulationData = genLoading(
 
 const uploadResourse = genLoading(async (file: File) => {
   const url = await postFile(`fusion/upload/file`, { file });
-  if (url.includes('//')) {
-    return url
+  if (url.includes("//")) {
+    return url;
   }
   if (import.meta.env.DEV && import.meta.env.VITE_STATIC) {
-    return `${import.meta.env.VITE_STATIC}${url}` 
+    return `${import.meta.env.VITE_STATIC}${url}`;
   } else {
-    return url
+    return url;
   }
 });
 

+ 0 - 47
src/example/fuse/router.ts

@@ -2,11 +2,7 @@ import { createRouter, createWebHashHistory } from "vue-router";
 
 
 import Overview from "./views/overview/index.vue";
-import OverviewQuery from "./views/overview/query.vue";
 import Tabulation from "./views/tabulation/index.vue";
-import QueryTabulation from "./views/tabulation/query.vue";
-import { computed, ref, watch, watchEffect } from "vue";
-import { inRevise } from "@/utils/shared";
 
 export const history = createWebHashHistory();
 export const router = createRouter({
@@ -19,46 +15,3 @@ export const router = createRouter({
     { path: '/:pathMatch(.*)*',  redirect: '/overview' } 
   ],
 });
-
-const params = ref<Record<string, string | undefined>>({})
-const updateParams = () => {
-  const hash = location.hash
-  const ndx = hash.indexOf('?')
-  const sParams = new URLSearchParams(hash.substring(ndx));
-  const rParams: Record<string, string | undefined> = {};
-  [...sParams.entries()].forEach(item => {
-    rParams[item[0]] = item[1]
-  })
-  if (inRevise(rParams, params.value)) {
-    params.value = rParams
-  }
-}
-watch(params, () => {
-  const sParams = new URLSearchParams();
-  for (const key in params.value) {
-    params.value[key] && sParams.append(key, params.value[key])
-  }
-  const ndx = location.hash.indexOf('?')
-  location.replace(location.hash.substring(0, ~ndx ? ndx : undefined) + '?' + sParams.toString())
-}, {deep: true})
-
-updateParams()
-window.addEventListener('hashchange', updateParams)
-
-export const tabulationId = computed({
-  get() {
-    return params.value.tabulationId
-  },
-  set(tabulationId: string) {
-    params.value.tabulationId = tabulationId
-  }
-})
-
-export const overviewId = computed({
-  get() {
-    return params.value.overviewId
-  },
-  set(overviewId: string) {
-    params.value.overviewId = overviewId
-  }
-})

+ 1 - 1
src/example/fuse/store.ts

@@ -1,7 +1,7 @@
 import { Ref, ref } from "vue";
 import { StoreData } from "@/core/store/store";
 import { PaperKey } from "../components/slide/actions";
-import { tabulationId, overviewId } from './router'
+import { overviewId, tabulationId } from "../env";
 
 
 export const tableCoverKey = '__tableCoverKey'

+ 2 - 1
src/example/fuse/views/overview/header.vue

@@ -30,7 +30,8 @@ import { Group } from "konva/lib/Group";
 import { Mode } from "@/constant/mode.ts";
 import { lineLen } from "@/utils/math.ts";
 import { repTabulationStore } from "../tabulation/gen-tab.ts";
-import { overviewId, router, tabulationId } from "../../router.ts";
+import { router } from "../../router.ts";
+import { overviewId, tabulationId } from "@/example/env.ts";
 
 const draw = useDraw();
 

+ 1 - 1
src/example/fuse/views/tabulation/header.vue

@@ -22,7 +22,7 @@ import { getImage as getResourceImage } from "@/utils/resource.ts";
 import { nextTick } from "vue";
 import { tabulationData } from "../../store.ts";
 import { Mode } from "@/constant/mode.ts";
-import { tabulationId } from "../../router.ts";
+import { tabulationId } from "@/example/env.ts";
 
 const draw = useDraw();