在VueJS中更新axios URL中的值

j13ufse2  于 2023-02-12  发布在  iOS
关注(0)|答案(4)|浏览(153)

我试图更新'this.counts'值在我的axios称为URL时,一个按钮被点击。有人能帮我解决这个问题吗?谢谢

.get(
          "https://myurl/results.json" +
            query +
            `&num_ranks=$**{this.counts}**` 

data: function () {
    return {
      counts: 2
};

methods: {
    //number added to the Axios URL to display load more results
    loadMore() {
      if (this.loadMore) {
        this.counts += 10;
      }
    },
}   

 <button                
            @click="loadMore">
            Load more {{ counts }}
          </button>
rhfm7lfc

rhfm7lfc1#

您需要的是在axios调用中使用params。

axios.get('https://myurl/results.json', { params: { num_ranks: this.counts } });

参数将附加到您正在调用的url。如果您有更多的参数,只需将它们放在params中:{...}

axios.get('https://myurl/results.json', { 
 params: { 
  param1: this.result, 
  param2: this.result2, 
  param3: this.result3 
 } 
});
pnwntuvh

pnwntuvh2#

为axios API请求创建一个特定函数,并在单击按钮时调用它(在loadMore()中调用)。

<template>
  <button @click="loadMore">Load more {{ counts }}</button>
</template>

<script>
export default {
  data() {
    return {
      counts: 0
    }
  },
  methods: {
    loadMore() {
      if (this.loadMore) {
        this.counts += 10;
        this.getMore()
      }
    },
    getMore() {
      // Axios call here
      axios.get("https://myurl/results.json" + query + `&num_ranks=$**{this.counts}**`)
    }
  }
}
</script>
bjg7j2ky

bjg7j2ky3#

你可以使用URLSearchParams来获取url参数的名称,并在你的代码中进行修改。

const url = window.location.href // get the url from current page
const searhParams = new URLSearchParams(url);
if (searchParams.has('name of the param in url')) {
 let count = searchParams.get('param in url');
 loadMore(count); // you pass as a param to loadMore function or do it inside that function
}

以下是医生提供的更多帮助:https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

72qzrwbm

72qzrwbm4#

我发现缺少的一件事是,在counts变量更新时,Axios API应该被重新触发以获取新的响应。如果你重新触发它,它应该工作。你可能需要检查你的API。
下面是一个虚拟API演示,它将counts作为查询参数,并在每次更新counts变量时获取响应。

Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data() {
    return {
      counts: 0
    }
  },
  methods: {
    loadMore() {
      if (this.loadMore) {
        this.counts += 1;
        this.getMore()
      }
    },
    getMore() {
      console.clear()
      // Axios call here
      axios.get(`https://jsonplaceholder.typicode.com/comments?postId=${this.counts}`).then(res => {
       console.log(res)
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.3.2/axios.min.js" integrity="sha512-NCiXRSV460cHD9ClGDrTbTaw0muWUBf/zB/yLzJavRsPNUl9ODkUVmUHsZtKu17XknhsGlmyVoJxLg/ZQQEeGA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="loadMore">Load more {{ counts }}</button>
</div>

相关问题