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) }) } }
关键说明
- 独立存储评论文本:通过
commentTexts对象,以每个offer的ID作为key,确保不同offer的评论内容互不干扰 - 传递Offer ID:点击按钮时直接将当前offer的ID传入
createComment方法,无需额外获取元素ID - v-for优化:添加
:key="offer.id"是Vue列表渲染的最佳实践,避免组件复用导致的异常行为
内容的提问来源于stack exchange,提问作者ILYASEM
相关产品推荐
相关产品推荐

