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

Alpine.js如何在页面刷新后保存动态添加的学生数据?

要实现页面刷新后保留添加的学生数据,核心是把数据持久化到浏览器的localStorage中——当前你的persons仅存在内存里,页面刷新就会被重置。下面是具体修改方案:

1. 调整JavaScript代码,实现数据持久化

修改addRemove函数,让persons从localStorage读取初始值,添加学生时同步更新存储:

function addRemove() {
  return { 
    newFirst: '', 
    newLast: '',
    // 从localStorage读取数据,无数据则初始化空数组
    persons: JSON.parse(localStorage.getItem('addedPersons')) || [],
    addRemoveSubmit() {
      // 新增学生数据到数组头部
      this.persons = [{ 
        first: this.newFirst, 
        last: this.newLast
      }, ...this.persons];
      // 将数组转为字符串存入localStorage
      localStorage.setItem('addedPersons', JSON.stringify(this.persons));
      // 重置下拉框选中状态
      this.newLast = '';
    }
  }
}

注:localStorage仅支持存储字符串,所以用JSON.stringify和JSON.parse处理数组的存储与读取。

2. 修正HTML结构问题

你的模板存在标签嵌套不规范的问题,会导致渲染异常,同时补上缺失的闭合标签:

<div x-data="addRemove()">
  <form x-on:submit.stop.prevent="addRemoveSubmit">
    <!-- 该下拉菜单是一个Laravel组件 -->
    <select x-model="newLast" id="last" wire:model="Customer_Name">
      <option value="" selected>分配学生</option>
      @foreach($posts as $post)
        <option value="{{ $post->First_Name }} {{ $post->Last_Name }}" name="Customer_Name">
          {{ $post->First_Name }} {{ $post->Last_Name }}
        </option>
      @endforeach
    </select>
    <button type="submit">添加学生</button>
    <!-- 用table包裹tr,保证表格结构合法 -->
    <table>
      <template x-for="(person, index) in persons" :key="index">
        <tr>
          <td x-text="person.last"></td>
        </tr>
      </template>
    </table>
  </form>
</div>

说明:

  • 补上了<select>的闭合标签,移除了<option>内无效的<br>标签
  • 用<table>包裹<tr>,避免非表格元素直接嵌套tr导致的渲染问题
  • 简化了x-for的遍历源,persons本身已是数组,无需用Object.values()转换

额外提示

  • 若要清除已保存的数据,可在浏览器控制台执行localStorage.removeItem('addedPersons'),或添加一个清除按钮触发该操作
  • 如果你需要后端同步保存数据,可在添加学生时调用Livewire的后端方法,将数据存入数据库,页面刷新时从后端加载数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:36:05