0

我正在做一个项目,我正在使用 axios get 从我的后端 laravel 获取 api 数据,并使用它的属性在我的组件的已安装部分中连接一个通道。

我正在通过 axios get 获取 api/user,其中包含

{
  "id": 1,
  "name": "admin",
  "email": "admin@company.com",
  "email_verified_at": null,
  "created_at": "2019-08-17 10:06:14",
  "updated_at": "2019-11-27 02:03:30",
  "phone_number": "+12345678911",
  "phone_number_verified": 0,
  "company_id": 1,
  "verification_code": "",
  "signature": "",
  "signature_image": null,
}

以下是我如何通过 axios 从我的 laravel 后端获取用户数据:

mounted() {
  this.$http
    .get('/api/user')
    .then(response => ( this.user = response.data ))
    .catch(error => console.log(error))
},

然后在我的 data() 部分中将其声明为空数组,如下所示:

data() {
  return {
    user: [],
  };
},

我可以通过 {{ user.id }} 在我的模板中访问属性,例如 id,当我尝试在 mount() 部分中访问它时,它给了我一个对象,但是当我尝试 console.log(this. user.id) 在挂载中,它会抛出 undefined 。我需要在已安装部分访问 this.user.id 的原因是因为我使用它来连接我通过 Laravel Echo 使用的通道,如下所示:

mounted() {
  this.$http
    .get('/api/user')
    .then(response => ( this.user = response.data ))
    .catch(error => console.log(error))

  this.$echo
    .channel(`new-notification.${this.user.id}`)
    .listen('NewNotification', (data) => {
    // eslint-disable-next-line no-alert
      this.notifications.unshift(data);
    });
},

我对 Vue 还很陌生,我不知道我在这方面做错了什么。如果有人能指出我做错了什么或者有更好的方法来做这件事,那将是非常有帮助的。

4

1 回答 1

0

问题是console将在 api 调用响应之前运行。你可以打电话async试试。

mounted() {
  this.fetchApi();
},
methods:{
  fetchApi: async function(){
    let response = await this.$http
     .get('/api/user');
    this.user = response.data;
    this.$echo
    .channel(`new-notification.${response.data.id}`)
    .listen('NewNotification', (data) => {
    // eslint-disable-next-line no-alert
      this.notifications.unshift(data);
    });
  }
}
于 2020-04-09T10:30:15.603 回答