Jelajahi Sumber

feat(news-edit): 修复页面参数获取逻辑,使用 onLoad 钩子获取参数

mcbaiyun 2 minggu lalu
induk
melakukan
432d961a10

+ 44 - 0
docs/uni-app 页面参数获取问题与修复.md

@@ -0,0 +1,44 @@
+# uni-app 页面参数获取问题与修复
+
+## 问题描述
+在 uni-app Vue 3 setup 环境中,页面跳转时传递的参数(如 `id`)在 `onMounted` 钩子中无法正确获取,导致控制台无输出或功能异常。
+
+## 问题原因
+最初尝试使用 `getCurrentPages()` 获取当前页面的 `options` 参数,但这种方法在 uni-app 的 Vue 3 setup 中不可靠。页面参数应在页面生命周期的 `onLoad` 钩子中获取,而不是在 `onMounted` 中通过全局方法获取。
+
+## 解决方法
+1. 导入 `onLoad` 钩子:`import { onLoad } from '@dcloudio/uni-app'`
+2. 定义响应式参数对象:`const query = ref<Record<string, string>>({})`
+3. 在 `onLoad` 中设置参数:
+   ```typescript
+   onLoad((options) => {
+     query.value = options || {}
+   })
+   ```
+4. 在 `onMounted` 中使用 `query.value.id` 检查和处理参数。
+
+## 经验教训
+- uni-app 中,页面参数的获取必须使用 `onLoad` 钩子,这是页面生命周期的标准方式。
+- 避免使用 `getCurrentPages()` 来获取参数,尤其在 Vue 3 setup 中。
+- 确保参数处理逻辑在正确的生命周期钩子中执行,以保证数据可用性。
+- 调试时,可在 `onLoad` 和 `onMounted` 中添加 `console.log` 来验证参数获取时机。
+
+## 相关代码片段
+```typescript
+import { ref, onMounted } from 'vue'
+import { onLoad } from '@dcloudio/uni-app'
+
+const query = ref<Record<string, string>>({})
+
+onLoad((options) => {
+  query.value = options || {}
+})
+
+onMounted(async () => {
+  const id = query.value.id || ''
+  if (id) {
+    console.log('Detected id:', id)
+    // 处理编辑逻辑
+  }
+})
+```

+ 11 - 5
src/pages/doctor/manage/news-edit.vue

@@ -41,10 +41,15 @@
 
 <script setup lang="ts">
 import { ref, onMounted, nextTick, computed } from 'vue'
+import { onLoad } from '@dcloudio/uni-app'
 import CustomNav from '@/components/custom-nav.vue'
 import { createNews, updateNews, uploadNewsImage, getNewsById } from '@/api/news'
 
-const query: Record<string, string> = (((globalThis as any).getCurrentPages ? (globalThis as any).getCurrentPages().slice(-1)[0]?.options : {}) as Record<string, string>) || {}
+const query = ref<Record<string, string>>({})
+
+onLoad((options) => {
+  query.value = options || {}
+})
 
 const title = ref('')
 const summary = ref('')
@@ -175,15 +180,15 @@ const save = async () => {
   if (saving.value) return
   saving.value = true
   try {
-    if (query.id) {
+    if (query.value.id) {
       // 编辑
       const payload = {
-        id: query.id,
+        id: query.value.id,
         title: title.value,
         content: content.value,
         summary: summary.value
       }
-      const res: any = await updateNews(query.id, payload)
+      const res: any = await updateNews(query.value.id, payload)
       const r = res?.data ?? res
       if (r && r.code === 200) {
         uni.showToast({ title: '更新成功', icon: 'success' })
@@ -221,8 +226,9 @@ const cancel = () => {
 
 onMounted(async () => {
   // 如果是编辑,读取 id 并可调用接口拉取详情(这里模拟)
-  const id = query.id || ''
+  const id = query.value.id || ''
   if (id) {
+    console.log('Detected id:', id)
     // 编辑:使用接口拉取真实数据
     try {
       const resp: any = await getNewsById(id)