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

Vue2中如何从HTML的id字段提取ID并通过Axios发送?

Vue2 动态获取Offer ID提交评论解决方案

原代码存在的问题

  • 所有评论框绑定了同一个text变量,输入时会同步所有框的内容,无法独立输入
  • createComment方法未接收对应offer的ID,无法将评论关联到指定的offer

修正方案及完整代码

HTML 部分

<div v-for="offer in offers" :key="offer.id">
  <p>{{ offer.description }}</p>

  <div class="form-group col-md-9">
    <b-form-textarea 
      :id="`${offer.id}`" 
      placeholder="Comment!" 
      rows="1" 
      v-model="commentTexts[offer.id]"
    ></b-form-textarea>
    <button @click="createComment(offer.id)" class="button btn btn-success">Send!</button>
  </div>
</div>

JS 部分

data () {
  return {
    offers: [
      {id: 1, description: "some"},
      {id: 2, description: "another"},
    ],
    commentTexts: {} // 存储每个offer对应的独立评论文本
  }
},
methods: { 
  createComment(offerId) {
    // 组装提交数据
    const formData = { 
      text: this.commentTexts[offerId],
      offer_related: offerId
    } 

    // 发送POST请求
    axios.post(`/api/v1/comments/`, formData)
      .then(() => {
        // 请求成功后清空当前评论框
        this.commentTexts[offerId] = ''
      })
      .catch(err => {
        console.error('评论提交失败:', err)
      })
  }
}

关键说明

  1. 独立存储评论文本:通过commentTexts对象,以每个offer的ID作为key,确保不同offer的评论内容互不干扰
  2. 传递Offer ID:点击按钮时直接将当前offer的ID传入createComment方法,无需额外获取元素ID
  3. v-for优化:添加:key="offer.id"是Vue列表渲染的最佳实践,避免组件复用导致的异常行为

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 06:57:15