You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt中router.push无法自动跳转,控制台报child is null错误求助

Nuxt中router.push携带参数后页面不跳转,控制台报错Uncaught (in promise) TypeError: child is null

问题详情

点击“预订(Réserver)”按钮后,URL已正确携带产品ID、名称、价格参数,但页面无法自动跳转,刷新页面后功能恢复正常;控制台抛出错误:Uncaught (in promise) TypeError: child is null。

相关代码

按钮代码

<button @click="reserveProduct" class="flex w-full items-center justify-center rounded-md border border-transparent bg-blue-500 px-8 py-3 text-base font-medium text-white hover:bg-blue-400 active:scale-105 transition-all">
Réserver
</button>

router.push脚本

const reserveProduct = () => {
  router.push({
    name: 'contact',
    query: { productId: product.value.id, productName: product.value.title, productPrice: product.value.price,},
  });
};

nuxt.config.ts配置

router: {
  extendRoutes(routes, resolve) {
    routes.push(
      {
        path: '/products/:productId',
        component: '~/pages/[productId].vue',
        name: 'product-details',
        
      },
      {
        path: '/contact',
        name: 'contact',
        component: resolve(__dirname, 'pages/contact.vue'),
      }
    );
  }
}

解决方案

1. 捕获router.push的Promise异常

router.push返回Promise,未处理的异常会阻断页面跳转流程。修改跳转函数添加异常捕获:

const reserveProduct = async () => {
  try {
    await router.push({
      name: 'contact',
      query: { 
        productId: product.value.id, 
        productName: product.value.title, 
        productPrice: product.value.price 
      },
    });
  } catch (err) {
    console.error('跳转失败:', err);
  }
};

2. 排查contact页面的DOM渲染问题

child is null报错通常和组件渲染时找不到目标DOM元素有关:

  • 确保contact页面中所有操作DOM的代码都放在onMounted钩子内,或使用nextTick确保DOM已完成渲染。
  • 检查页面中是否存在依赖异步数据的DOM操作,比如在数据未返回时就尝试访问DOM节点。

3. 验证路由配置是否冲突

如果pages目录下已存在contact.vue,Nuxt会自动生成对应的路由,手动在extendRoutes中添加可能导致路由冲突。删除extendRoutes中的contact路由配置,让Nuxt自动生成:

router: {
  extendRoutes(routes, resolve) {
    routes.push(
      {
        path: '/products/:productId',
        component: '~/pages/[productId].vue',
        name: 'product-details',
        
      }
    );
  }
}

4. 确保product.value状态有效

点击按钮时确认product.value已正确初始化,避免因数据未加载完成导致的异常:

const reserveProduct = () => {
  if (!product.value?.id) return;
  router.push({
    name: 'contact',
    query: { 
      productId: product.value.id, 
      productName: product.value.title, 
      productPrice: product.value.price 
    },
  });
};

内容的提问来源于stack exchange,提问作者cnihoul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 00:26:19