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

Alpine.js调用store报错:无法读取undefined的items属性求解决方案

Alpine.js Store循环报错问题解决

问题描述

在Alpine组件内通过store实现for循环时,出现错误:Uncaught TypeError: Cannot read properties of undefined (reading 'items')。代码结构如下:

HTML代码

<div class="content__mid" x-data="">
  <template x-for="item in $store.products.items" :key="item.id">
    <p class="content__mid-item" x-text="item.title"></p>
  </template>
</div>

JavaScript代码

import Alpine from 'alpinejs'
 
Alpine.store('products', {
  items: [
    {
      id: 1,
      title: 'Aspirin',
      country: 'USA',
      manufacturer: 'Bangladesh',
      price: '120',
      validDate: '02.10.2024'
    },
    {
      id: 2,
      title: 'Aspirin',
      country: 'Italy',
      manufacturer: 'Bangladesh',
      price: '120',
      validDate: '02.10.2024'
    }
  ]
})
 
Alpine.start()

错误原因

核心问题是store未被正确初始化并注入Alpine环境,导致组件无法读取$store.products,具体诱因:

  • HTML引入脚本时未声明为ES模块(type="module"),浏览器无法解析import语法,Alpine和store代码未执行。
  • 脚本加载顺序错误,组件渲染时store还未完成初始化。

解决方案

  1. 正确引入ES模块脚本
    在HTML中引入script.js时,必须添加type="module"属性,确保浏览器按ES模块规则解析代码:
<script type="module" src="script.js"></script>
  1. 确保脚本加载顺序
    将脚本标签放在<body>末尾(组件DOM之后),或添加defer属性,保证DOM渲染前store已完成初始化。

  2. 验证store可用性
    在浏览器控制台输入Alpine.store('products'),若返回store对象则初始化成功;若返回undefined,则检查脚本加载路径和属性是否正确。

修正后的完整HTML示例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Alpine Store Example</title>
</head>
<body>
  <div class="content__mid" x-data="">
    <template x-for="item in $store.products.items" :key="item.id">
      <p class="content__mid-item" x-text="item.title"></p>
    </template>
  </div>

  <!-- 正确引入ES模块脚本 -->
  <script type="module" src="script.js"></script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 08:22:29