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

Nuxt中Pug模板无法使用变量问题排查

Nuxt中Pug循环访问script变量报Cannot read properties of undefined (reading 'length')错误的排查方案

1. 变量未初始化导致渲染时为undefined

确保pages变量在组件初始化时就有默认值,避免页面首次渲染时变量还未赋值:

<script>
export default {
  data() {
    return {
      pages: [] // 初始化为空数组,防止undefined
    }
  },
  async mounted() {
    // 异步获取数据后赋值
    this.pages = await fetchYourPageData()
  }
}
</script>

2. 异步数据加载方式错误

如果pages是通过Nuxt的asyncData或fetch方法获取,需确保数据正确返回并绑定到组件实例:

  • 使用asyncData的正确写法:
<script>
export default {
  async asyncData() {
    const pages = await fetchYourPageData()
    return { pages } // 必须将数据返回,Nuxt会自动注入到组件
  }
}
</script>

注意:asyncData中不能使用this,直接返回数据对象即可。

3. Pug循环语法的变量引用错误

检查Pug代码中循环的变量名是否正确,避免笔误:

ul
  each page in pages  <!-- 确认变量名是pages,而非其他拼写错误 -->
    li= page.title

4. 跨组件变量未通过props传递

如果pages定义在父组件,子组件需通过props接收后才能使用,不能直接访问父组件作用域的变量:

<!-- 父组件 -->
<template lang="pug">
  child-component(:pages="pages")
</template>

<!-- 子组件 -->
<script>
export default {
  props: {
    pages: {
      type: Array,
      default: () => [] // 同样设置默认空数组
    }
  }
}
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 05:42:05