【问题标题】:Vue.js, How to send object in api link via axios?Vue.js,如何通过 axios 在 api 链接中发送对象?
【发布时间】:2021-12-12 05:42:04
【问题描述】:

所以我有GET|HEAD api:api/users/{user},它调用函数App\Http\Controllers\Api\UserController@show。 Laravel 中的这个函数是:

   public function show($id){
    return new UserShowResource(User::findOrFail($id));
}

如何将变量 id 发送到我的函数。我在某个地方找到了这个:

const helpVar = axios.get('/api/users/{this.$route.params.id}').then(response => {
           this.users = response.data;
           this.loading = false;
             
        });

但它不起作用。我试过axios.get('/api/users/1'),它返回给我id=1的用户,所以问题出在axios中的这个链接。

【问题讨论】:

  • {this.$route.params.id} 输出是什么?
  • 我做了console.log(this.$route.params.id},它返回1(或其他数字,取决于用户ID)

标签: javascript api vue.js axios


【解决方案1】:

您的代码不起作用,因为您使用的是简单的引号。当您尝试使用 template literals 进行插值时,您必须将代码更改为:


const helpVar = axios.get(`/api/users/${this.$route.params.id}`).then(response => {
           this.users = response.data;
           this.loading = false;
             
        });
  • 注意 '' 更改为 ``

【讨论】:

  • 对于以后会发现这个问题的人来说,{this...}之前应该有$,所以完整正确的语法是:axios.get(/api/users/${this.$route.params.id})
  • 感谢@Raskoljnikovic,一直在使用C#,忘记添加$
【解决方案2】:

我认为你应该使用 ` 而不是 ' 所以它可以通过 {this.$route.params.id} ;


const helpVar = axios.get(`/api/users/{this.$route.params.id}`).then(response => {
           this.users = response.data;
           this.loading = false;
             
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 2019-12-30
    • 1970-01-01
    • 2018-06-20
    • 2013-09-02
    • 2016-09-12
    相关资源
    最近更新 更多