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

Alpine JS问题:仅声明一个元素却显示两个条目

问题原因及修复方案

你初始化的questions数组只有1个元素,但页面显示2个条目,主要是以下原因导致:

1. HTML结构错误(最直接原因)

你的<select>标签存在语法错误:把一个class属性单独写在了标签内部的一行,这会破坏DOM结构,导致AlpineJS的x-for指令渲染异常。

错误代码片段:

<select class="select select-bordered w-full" x-model="question.type"
    x-bind:name="'questions['+index+'][type]'">
    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
    <option value="text">Text</option>
    <!-- 其他选项 -->
</select>

修复方法:把多余的class属性合并到select标签的class属性中,修正后的代码:

<select class="select select-bordered w-full mt-1 block rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
        x-model="question.type"
        x-bind:name="'questions['+index+'][type]'">
    <option value="text">Text</option>
    <option value="textarea">Long Text</option>
    <option value="radio">Multiple Choice</option>
    <option value="checkbox">Checkboxes</option>
</select>

2. 可选优化:更换x-for的key值

你当前用index作为x-for的:key,虽然不会直接导致重复渲染,但如果后续数组元素有删除/排序操作,容易引发渲染异常。建议给每个question对象添加唯一标识作为key:

修改x-data的初始化逻辑:

questions: [{
    id: Date.now(), // 生成唯一ID
    content: '',
    type: 'text'
}],
addQuestion() {
    this.questions.push({
        id: Date.now(),
        content: '',
        type: 'text'
    })
},

同步修改x-for的key:

<template x-for="(question, index) in questions" :key="question.id">

额外排查点

  • 检查页面是否有其他JS代码意外修改了questions数组
  • 清除浏览器缓存,避免旧代码缓存干扰

内容的提问来源于stack exchange,提问作者Felipe Peña

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 06:15:12