refactor(导航): 统一微信小程序导航逻辑并简化环境判断

移除环境判断分支逻辑,统一使用微信小程序导航方式
清理无用代码并优化登录状态处理
更新文章组件以支持外部传入登录状态
删除index.html中冗余的脚本代码
This commit is contained in:
34701892@qq.com 2025-12-26 14:35:00 +08:00
parent 11fdfc16c6
commit 1f21f01bde
6 changed files with 70 additions and 225 deletions

View File

@ -15,70 +15,6 @@
</script>
<!-- <script type="text/javascript" src="//res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> -->
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script type="text/javascript">
console.log("🚀 ~ window.location.href:", window.location.href);
const urlParams = parseUrlParams();
// wx.miniProgram.postMessage({
// data: {
// type: "share_info",
// userType: urlParams?.userType || null,
// phone: urlParams?.phone || null,
// id: urlParams?.id || null,
// },
// });
// const currentRoute = getCurrentRoute();
// console.log("当前纯路由地址:", currentRoute); // 输出:/pages/detail/indexNewsInfo
function getCurrentRoute() {
// 1. 获取hash处理hash为空的边界情况
const hash = window.location.hash || "";
if (!hash || hash === "#") return "";
// 2. 去掉开头的#,得到 hash 主体(如 /pages/detail/indexNewsInfo?id=xxx
const hashMain = hash.slice(1);
// 3. 拆分路由和参数(以?为分隔符,取第一部分)
const routePart = hashMain.split("?")[0];
// 4. 兼容:去除路由前后多余的空格(防异常)
const pureRoute = routePart.trim();
return pureRoute;
}
// ========== 核心URL参数解析函数 ==========
function parseUrlParams() {
const params = {};
let search = window.location.search; // 获取 ? 后的参数(如 ?name=test&age=18
let hash = window.location.hash; // 获取 # 后的参数(如 #/pages/index?name=test
// 步骤1优先解析 search 参数history模式
if (search) {
// 去掉开头的 ?,拆分参数对
const searchParams = new URLSearchParams(search.slice(1));
searchParams.forEach((value, key) => {
// 解码中文/特殊字符(解决小程序传参中文乱码)
params[key] = decodeURIComponent(value);
});
}
// 步骤2解析 hash 中的参数Uniapp H5 默认 hash 路由,参数可能在 # 后)
if (hash) {
// 提取 hash 中 ? 后的部分(如 #/pages/index?name=test → ?name=test
const hashQuery = hash.split("?")[1];
if (hashQuery) {
const hashParams = new URLSearchParams(hashQuery);
hashParams.forEach((value, key) => {
params[key] = decodeURIComponent(value); // 解码
});
}
}
return params;
}
</script>
<!-- <script
type="text/javascript"
@ -99,76 +35,6 @@
<div id="app"><!--app-html--></div>
<script type="module" src="/src/main.ts"></script>
<script>
// // 路由变化的处理逻辑
// function handleRouteChange() {
// console.log("🚀 ~ handleRouteChange ~ handleRouteChange:");
// const { route, params } = parseH5Route();
// console.log("H5地址变化", {
// 路由: route, // 如 "/pages/detail/indexNewsInfo"
// 参数: params, // 如 {id: "98511"}
// });
// if (route === "/pages/detail/indexNewsInfo") {
// wx.miniProgram.navigateTo({
// url: "/pages/webView/index?url=" + encodeURIComponent(shareUrl),
// });
// }
// // 更新全局变量供Uniapp页面使用
// window.currentH5Route = { route, params };
// // 派发自定义事件供Vue页面监听
// window.dispatchEvent(new CustomEvent("h5RouteChanged", { detail: { route, params } }));
// }
// // 监听hash变化Uniapp默认hash路由
// window.addEventListener("hashchange", handleRouteChange);
// // 监听history变化如浏览器前进/后退、history.pushState
// window.addEventListener("popstate", handleRouteChange);
// // 初始化解析
// handleRouteChange();
// // 页面卸载时移除监听,防止内存泄漏
// window.addEventListener("beforeunload", () => {
// window.removeEventListener("hashchange", handleRouteChange);
// window.removeEventListener("popstate", handleRouteChange);
// });
// // 解析H5路由兼容hash/history
// function parseH5Route() {
// let route = "";
// let params = {};
// const { hash, pathname, search } = window.location;
// // 处理Uniapp默认的hash路由
// if (hash) {
// const hashMain = hash.slice(1);
// const [routePart, paramPart] = hashMain.split("?");
// route = routePart;
// // 解析hash参数
// if (paramPart) {
// const paramArr = paramPart.split("&");
// paramArr.forEach((item) => {
// const [key, value] = item.split("=");
// if (key) params[key] = decodeURIComponent(value || "");
// });
// }
// }
// // 处理history路由
// else {
// route = pathname;
// // 解析search参数
// if (search) {
// const searchParams = new URLSearchParams(search.slice(1));
// searchParams.forEach((value, key) => {
// params[key] = decodeURIComponent(value);
// });
// }
// }
// return { route, params };
// }
</script>
<!-- <script type="text/javascript">
var link = location.href.split("#")[0];
console.log("🚀 ~ link:", link);

View File

@ -155,36 +155,31 @@ import wx from "weixin-js-sdk";
const clickItem = ref({});
function goDetail(item) {
clickItem.value = item;
// if (uni.getStorageSync("token")) {
// uni.navigateTo({
// url: `/pages/detail/indexNewsInfo?id=${item.news_id}`,
// });
// } else {
// uni.navigateTo({
// url: "/pages/login/indexMini",
// });
// }
let phone = props.userParams.phone || "";
let userType = props.userParams.userType || "";
if (judgeRuntimeEnv().isWxMiniWebview) {
let shareUrl =
"https://cankao.cs.com.cn/jnh/#/pages/detail/indexNewsInfo?id=" +
// "http://localhost:8881/jnh/#/pages/detail/indexNewsInfo?id=" +
item.news_id +
"&phone=" +
uni.getStorageSync("token") +
"&userType=" +
userType.value;
// if (judgeRuntimeEnv().isWxMiniWebview) {
let shareUrl =
"https://cankao.cs.com.cn/jnh/#/pages/detail/indexNewsInfo?id=" +
// "http://localhost:8881/jnh/#/pages/detail/indexNewsInfo?id=" +
item.news_id +
"&phone=" +
uni.getStorageSync("token") +
"&userType=" +
userType.value;
wx.miniProgram.navigateTo({
url: "/pages/webView/index?url=" + encodeURIComponent(shareUrl),
});
} else {
uni.navigateTo({
url: `/pages/detail/indexNewsInfo?id=${item.news_id}&phone=${phone}&userType=${userType}`,
});
}
wx.miniProgram.navigateTo({
url: "/pages/webView/index?url=" + encodeURIComponent(shareUrl),
success: (res) => {
console.log("🚀 调用小程序跳转navigateTo:", res);
},
});
// } else {
// uni.navigateTo({
// url: `/pages/detail/indexNewsInfo?id=${item.news_id}&phone=${phone}&userType=${userType}`,
// });
// }
}
const LoginShow = ref(false);

View File

@ -2,9 +2,7 @@
<view class="main">
<text style="margin-left: 40rpx; margin-right: 40rpx; display: flex">
<text class="title">{{ props.data.title?.slice(0, 3) }}</text>
<text :class="['title', isLogin ? '' : 'mohu']">{{
props.data.title?.slice(3, props.data.title.length)
}}</text>
<text :class="['title', isLogin ? '' : 'mohu']">{{ props.data.title?.slice(3, props.data.title.length) }}</text>
</text>
<view class="author">
@ -22,9 +20,7 @@
<!-- 两个标签 start -->
<view class="r_r_tags">
<view
style="display: flex; margin-top: 20rpx; overflow-x: auto; width: 95vw"
>
<view style="display: flex; margin-top: 20rpx; overflow-x: auto; width: 95vw">
<view class="r_tags">
<view
class="tag"
@ -36,9 +32,7 @@
</view>
</view>
<view
style="display: flex; margin-top: 20rpx; overflow-x: auto; width: 100vw"
>
<view style="display: flex; margin-top: 20rpx; overflow-x: auto; width: 100vw">
<view class="r_tags">
<view
class="tag"
@ -53,10 +47,7 @@
<!-- 两个标签 end -->
<!-- 摘要 -->
<view
:class="['desc', isLogin ? '' : 'mohu']"
v-if="props.data.summary && !isDomestic"
>
<view :class="['desc', isLogin ? '' : 'mohu']" v-if="props.data.summary && !isDomestic">
<!-- <view class="bill_icon"></view> -->
{{ props.data.summary }}
</view>
@ -88,13 +79,7 @@
<script setup lang="ts">
import { ref } from "vue";
import {
onLaunch,
onShow,
onLoad,
onShareAppMessage,
onShareTimeline,
} from "@dcloudio/uni-app";
import { onLaunch, onShow, onLoad, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
// import articleMock from "@/mock/article.js";
const isLogin = ref(uni.getStorageSync("token"));
@ -107,6 +92,10 @@ const props = defineProps({
type: Boolean,
default: false,
},
isLogin: {
type: Boolean,
default: false,
},
});
const tagList1 = ref([
{
@ -140,6 +129,8 @@ const handleClick = (value: any) => {
onLoad((option) => {
type.value = option?.type || "list";
isLogin.value = props.isLogin ? true : uni.getStorageSync("token") ? true : false;
});
const handleSub = () => {

View File

@ -40,23 +40,17 @@ function doDetail(item) {
let phone = props.userParams.phone || "";
let userType = props.userParams.userType || "";
if (judgeRuntimeEnv().isWxMiniWebview) {
let shareUrl =
"https://cankao.cs.com.cn/jnh/#/pages/detail/indexNewsInfo?id=" +
item.news_id +
"&phone=" +
uni.getStorageSync("token") +
"&userType=" +
userType.value;
let shareUrl =
"https://cankao.cs.com.cn/jnh/#/pages/detail/indexNewsInfo?id=" +
item.news_id +
"&phone=" +
uni.getStorageSync("token") +
"&userType=" +
userType.value;
wx.miniProgram.navigateTo({
url: "/pages/webView/index?url=" + encodeURIComponent(shareUrl),
});
} else {
uni.navigateTo({
url: `/pages/detail/indexNewsInfo?id=${item.news_id}&phone=${phone}&userType=${userType}`,
});
}
wx.miniProgram.navigateTo({
url: "/pages/webView/index?url=" + encodeURIComponent(shareUrl),
});
}
async function getDomesticFn() {

View File

@ -34,7 +34,7 @@
</view> -->
<!-- 文章正文 start -->
<Article :data="data" :isDomestic="isDomestic" />
<Article :data="data" :isDomestic="isDomestic" :isLogin="isLogin" />
<!-- 分割 -->
<view class="line"></view>
<!-- 推荐栏目 -->
@ -124,7 +124,7 @@ onLoad(async (option: any) => {
columnName.value = res.data.columnName1;
newList(res.data.columnId1);
wxShare();
// wxShare();
wx.miniProgram.postMessage({
data: {
@ -143,11 +143,13 @@ onLoad(async (option: any) => {
if (option?.phone) {
uni.setStorageSync("token", option.phone);
// phone
let url = window.location.href;
url = url.replace(/phone=[^&]+&?/i, "");
// let url = window.location.href;
// url = url.replace(/phone=[^&]+&?/i, "");
//
window.location.href = url;
window.location.reload();
// window.location.href = url;
// window.location.reload();
isLogin.value = uni.getStorageSync("token") ? true : false;
}
// 12
@ -162,23 +164,10 @@ onLoad(async (option: any) => {
if (uni.getStorageSync("token") && Date.now() - shareTime > 24 * 60 * 60 * 1000) {
uni.removeStorageSync("token");
// 1766373354519
window.location.reload();
// window.location.reload();
isLogin.value = uni.getStorageSync("token") ? true : false;
}
}
// if (option?.into) {
// let shareUrl =
// "https://cankao.cs.com.cn/jnh/#/pages/detail/indexNewsInfo?id=" +
// option.id +
// "&phone=" +
// uni.getStorageSync("token") +
// "&userType=" +
// userType.value +
// "&into=1";
// wx.miniProgram.navigateTo({
// url: "/pages/webView/index?url=" + encodeURIComponent(shareUrl),
// });
// }
});
const newList = async (columnId: number) => {

View File

@ -106,25 +106,35 @@ export function judgeRuntimeEnv() {
const systemInfo = uni.getSystemInfoSync();
// 小程序环境包括webview的 platform 为 'devtools'(开发者工具)、'ios'、'android'
// 且不存在浏览器的 window.navigator 特征或UA不含浏览器标识
if (systemInfo.platform && !/(Chrome|Safari|Firefox)/i.test(navigator.userAgent)) {
// 进一步判断是否是微信小程序
if (navigator.userAgent.includes("miniProgram")) {
result.isWxMiniWebview = true;
}
} else {
result.isWxMiniWebview = false;
}
} catch (e) {
// uni.getSystemInfoSync 执行失败,说明不是小程序环境(如浏览器)
}
// 2. 检测微信小程序特有全局对象webview中会注入wx对象
if (typeof wx !== "undefined" && wx.miniProgram) {
result.isWxMiniWebview = true;
}
// // 2. 检测微信小程序特有全局对象webview中会注入wx对象
// if (typeof wx !== "undefined" && wx.miniProgram) {
// result.isWxMiniWebview = true;
// } else {
// result.isWxMiniWebview = false;
// result.isBrowser = true;
// }
// 3. 检测浏览器环境(兜底判断)
if (typeof window !== "undefined" && typeof document !== "undefined" && !result.isWxMiniWebview) {
result.isBrowser = true;
}
// // 3. 检测浏览器环境(兜底判断)
// if (typeof window !== "undefined" && typeof document !== "undefined" && !result.isWxMiniWebview) {
// result.isBrowser = true;
// result.isWxMiniWebview = false;
// } else {
// result.isWxMiniWebview = true;
// result.isBrowser = false;
// }
return result;
}