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

Vue中点击v-for列表项更新selected并发起Ajax请求的问题

问题解决方法

原代码存在几个核心问题,直接导致功能异常:

  • <a>标签不是表单输入控件,不支持v-model,这就是添加后出问题的原因;
  • 点击<a>会触发默认页面跳转,需要阻止该行为;
  • myMethod1里直接用selected是全局变量,未正确引用Vue实例的this.selected;
  • Topics未在data中声明,无法实现Vue响应式更新。

以下是修改后的完整代码:

JS代码

new Vue({
  el: "#app",
  data: {
    myId: "",
    selected: "",
    Topics: [], // 新增数组存储接口返回数据
    todos: [{"ForumId":41830,"Name":"test","Description":{"Text":"","Html":""},"ShowDescriptionInTopics":false,"AllowAnonymous":false,"IsLocked":false,"IsHidden":false,"RequiresApproval":false,"MustPostToParticipate":false,"DisplayInCalendar":false,"DisplayPostDatesInCalendar":false,"StartDate":null,"EndDate":null,"PostStartDate":null,"PostEndDate":null,"StartDateAvailabilityType":null,"EndDateAvailabilityType":null},{"ForumId":41863,"Name":"new forum","Description":{"Text":"","Html":""},"ShowDescriptionInTopics":false,"AllowAnonymous":false,"IsLocked":false,"IsHidden":false,"RequiresApproval":false,"MustPostToParticipate":false,"DisplayInCalendar":false,"DisplayPostDatesInCalendar":false,"StartDate":null,"EndDate":null,"PostStartDate":null,"PostEndDate":null,"StartDateAvailabilityType":null,"EndDateAvailabilityType":null}]
  },
  methods: {
    myMethod1(forumId) {
      // 直接更新selected为当前项的ForumId
      this.selected = forumId;
      
      const vm = this;
      $.ajax({
        url: `https://example.com/${vm.myId}/blogs/${this.selected}/topics/`,
        type: 'Get',
        headers: {
          accept: "application/json;odata=verbose"
        },
        success: function (data) {
          console.log(data);
          vm.Topics = data;
        }
      })
    }
  }
})

HTML代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h2>Todos:</h2>
  <!-- 用@click.prevent阻止默认跳转,同时传递当前item的ForumId -->
  <li v-for="(item, index) in todos">
    <a href="" @click.prevent="myMethod1(item.ForumId)">{{item.Name}}</a>
  </li>
  <!-- 可选:添加选中状态展示,方便测试 -->
  <p>当前选中的ForumId: {{selected}}</p>
</div>

关键修改说明:

  1. 移除<a>标签的v-model,改为在点击事件中直接传递item.ForumId,在方法内更新this.selected;
  2. 给@click添加.prevent修饰符,阻止a标签默认跳转行为,避免页面刷新;
  3. 在data中声明Topics数组,确保Vue能监听其变化;
  4. 修正myMethod1中selected的引用方式,改为this.selected,正确访问Vue实例变量。

修改后点击不同列表项时,selected会同步更新为对应项的ForumId,同时正常发起请求获取数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 20:01:10