简体   繁体   English

如何在Vue中传递函数参数以使用axios发出GET请求?

[英]How to pass function parameters in Vue to make a GET request using axios?

I'm trying to send a GET request with Vue instead of sending it with POSTMAN for my small learning project.我正在尝试使用 Vue 发送 GET 请求,而不是使用 POSTMAN 发送我的小型学习项目。 I have this code that handels that:我有这段代码可以处理:


<tr v-for="(cabinet, i) in cabinets">
    <td>{{ cabinet }}</td>
</tr>
<script>
const axios = require('axios');

export default {
    name: "Cabinets",
    data() {
      return {
          cabinets: []
      }
    },
    methods: {
        getCabinets($id) {
            axios({
                method: 'GET',
                url: 'user/{id}/cabinets'
            })
                .then(response => {
                    this.cabinets = response.data
                })
        }
    }
}
</script>

For some reason I'm unable to see how this should work excatly even after seeing many related questions.出于某种原因,即使在看到许多相关问题之后,我也无法看到它应该如何工作。 In POSTMAN I would do http://my.domain:PORT_NUMBER/user/815/cabinets .在 POSTMAN 中,我会做http://my.domain:PORT_NUMBER/user/815/cabinets How would I be able to pass the id 815 and test it/show the results in Vue?我如何能够通过 id 815 并在 Vue 中对其进行测试/显示结果? When running this in Postman I get a JSON response that looks like this:在 Postman 中运行它时,我得到一个如下所示的 JSON 响应:

[
    {
        "idOfCabinet": 666,
        "belongToUser": 815,
        "time": "2018-06-18 11:51:22",
        "toucher": "person1",
    },
    {
        "idOfCabinet": 23,
        "belongToUser": 815,
        "time": "2019-09-11 10:51:22",
        "toucher": "person3",
    }

]

You can use the mounted() function of the Vue instance, it will be triggered as soon as the component is mounted可以使用Vue实例的mounted()函数,组件一挂载就会触发

cf: https://v2.vuejs.org/v2/api/#mounted参考: https ://v2.vuejs.org/v2/api/#mounted

for example:例如:

<tr v-for="(cabinet, i) in cabinets">
    <td>{{ cabinet }}</td>
</tr>
<script>
const axios = require('axios');

export default {
  name: "Cabinets",
  data() {
    return {
      cabinets: []
    }
  },
  mounted() {
    axios({
      method: 'GET',
      // Use backticks to do string interpolation
      // Replace the id variable by the correct id definition (idk where you get it)
      url: `user/${this.$session.get('user').id}/cabinets`
    }).then(response => {
      this.cabinets = response.data
    })
  }
}
</script>

You can get the response using axios .您可以使用axios获得响应。

    axios.get('user/${$id}/cabinets')
      .then(response => {
        console.log(response)
        this.cabinets = response.data
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM