使用 watchEffect 监听url 参数 老是报错

来源:5-2 -使用Copilot快速获取博客数据,并渲染博客列表

一逐星一

2023-08-01

在这里输入<script setup>
import { ref, watchEffect } from 'vue';
import { useRouter } from 'vue-router';
import { getBlogList } from '@/api/blog';

// 获取路由对象
const route = useRouter();

// 定义列表和总数的ref
const blogList = ref([]);
const total = ref(0);

// 使用 watchEffect 监听url 参数 page pageSize category keyword 的变化 并获取博客列表和总数
watchEffect(() => {
  const { query } = route;
  const page = parseInt(query.page) || 1;
  const pageSize = parseInt(query.pageSize) || 3;
  const category = query.category || '';
  const keyword = query.keyword || '';

  // 调用api方法获取博客列表和总数
  getBlogList({ page, pageSize, category, keyword })
      .then((res) => {
        console.log('res', res)
        blogList.value = res.data.list;
        total.value = res.data.total;
      })
      .catch((error) => {
        // 处理错误情况
        console.error('获取博客列表失败:', error);
      });
});
</script>

<template>
  <main>
    <!-- 在这里使用获取到的博客列表和总数 -->
    <h1>Home</h1>
    <ul>
      <li v-for="blog in blogList" :key="blog.id">
        {{ blog.title }}
      </li>
    </ul>
    <p>Total: {{ total }}</p>
  </main>
</template>
代码

Home.vue:16 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘page’)
at Home.vue:16:31
at callWithErrorHandling (runtime-core.esm-bundler.js:158:18)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:166:17)
at ReactiveEffect.getter [as fn] (runtime-core.esm-bundler.js:1702:16)
at ReactiveEffect.run (reactivity.esm-bundler.js:178:19)
at doWatch (runtime-core.esm-bundler.js:1797:12)
at watchEffect (runtime-core.esm-bundler.js:1621:10)
at setup (Home.vue:14:1)
at callWithErrorHandling (runtime-core.esm-bundler.js:158:18)
at setupStatefulComponent (runtime-core.esm-bundler.js:7236:25)

写回答

1回答

双越

2023-08-01

https://img.mukewang.com/szimg/64c8a46e097bc23415880138.jpg

这是报错提示,具体在哪一行?你代码没有行数,我也看不出来

0
2
双越
回复
一逐星一
好👌继续往前学习
2023-08-01
共2条回复

程序员的 AI 启蒙课,ChatGPT 辅助开发 Vue3 项目

使用 ChatGPT+Copilot 快速开发仿简书项目,90% 代码由 AI 生成

839 学习 · 30 问题

查看课程