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

VueJS中点击按钮更新Axios URL里的this.counts值求助

解决点击按钮更新Axios请求URL中counts值的问题

你的代码存在几个关键问题:Axios请求仅在初始化时执行一次,更新counts后未重新发起请求;loadMore方法的判断逻辑错误;模板字符串语法也有问题。以下是修正后的完整方案:

1. 封装Axios请求为独立方法

把请求逻辑抽成单独方法,方便在counts更新后重复调用:

data() {
  return {
    counts: 2,
    // 可新增状态变量控制加载,避免重复请求
    isLoading: false
  };
},
methods: {
  // 封装请求方法
  fetchResults() {
    this.isLoading = true;
    this.$axios.get(
      `https://myurl/results.json${query}&num_ranks=${this.counts}`
    )
    .then(response => {
      // 处理接口返回的数据
      console.log(response.data);
    })
    .catch(error => {
      console.error('请求失败:', error);
    })
    .finally(() => {
      this.isLoading = false;
    });
  },
  loadMore() {
    // 修正判断逻辑:避免加载中重复触发,可根据实际需求补充更多判断(比如是否还有数据)
    if (this.isLoading) return;
    this.counts += 10;
    // 更新counts后立即重新发起请求
    this.fetchResults();
  }
},
// 页面初始化时调用请求,获取初始数据
created() {
  this.fetchResults();
}

2. 修正模板字符串语法

原代码中&num_ranks=$**{this.counts}**的多余**会导致语法错误,正确写法是&num_ranks=${this.counts},确保模板字符串能正确解析this.counts的值。

3. 按钮模板保持不变

你的按钮绑定逻辑是正确的,点击时会触发loadMore方法:

<button @click="loadMore" :disabled="isLoading">
  Load more {{ counts }}
</button>

(新增:disabled="isLoading"可防止用户在加载中重复点击)

这样修改后,每次点击按钮,counts会增加10,同时自动重新发起Axios请求,URL中的num_ranks参数会同步使用更新后的counts值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 08:50:22