refactor(微信分享): 将微信小程序消息发送逻辑从组件移到index.html

将微信小程序的消息发送逻辑从indexNewsInfo.vue组件中移除,改为在index.html中统一处理
添加URL参数解析功能以支持从URL获取分享参数
This commit is contained in:
34701892@qq.com 2025-12-25 15:19:22 +08:00
parent b63bd3703a
commit e8a9f2cb91
2 changed files with 72 additions and 42 deletions

View File

@ -1,7 +1,6 @@
<!DOCTYPE html>
<html>
<head>
<head>
<meta charset="UTF-8" />
<script>
var coverSupport =
@ -14,6 +13,53 @@
'" />'
);
</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">
const urlParams = parseUrlParams();
console.log("解析后的URL参数", urlParams); // 示例输出:{name: "张三", age: "20"}
wx.miniProgram.postMessage({
data: {
type: "share_info",
userType: urlParams?.userType || null,
phone: urlParams?.phone || null,
id: urlParams?.id || null,
},
});
// ========== 核心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"
src="//res.wx.qq.com/open/js/jweixin-1.6.0.js"
@ -27,9 +73,9 @@
<title></title>
<!--preload-links-->
<!--app-context-->
</head>
</head>
<body>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="/src/main.ts"></script>
<!-- <script type="text/javascript">
@ -107,6 +153,5 @@
error: function (error) {},
});
</script> -->
</body>
</body>
</html>

View File

@ -68,7 +68,7 @@
</template>
<script setup lang="ts">
import { ref } from "vue";
import { ref, onMounted, nextTick } from "vue";
import { onLoad, onShareAppMessage, onShareTimeline, onShow } from "@dcloudio/uni-app";
import { onReachBottom } from "@dcloudio/uni-app";
import { fetchArticleDetail, fetchArticleLike, fetchArticleFavorate } from "@/api/detail";
@ -152,21 +152,6 @@ onLoad(async (option: any) => {
window.location.reload();
}
}
console.log("准备发送消息到小程序");
if (typeof wx !== "undefined" && wx.miniProgram) {
wx.miniProgram.postMessage({
data: {
type: "share_info",
userType: option?.userType || null,
phone: option?.phone || null,
id: option?.id || null,
},
});
console.log("消息已发送");
} else {
console.log("非微信小程序环境,无法发送消息");
}
});
const newList = async (columnId: number) => {