【问题标题】:VueJS - Can't access assigned this.property declared within mounted() in mounted()VueJS - 无法访问在mounted() 中的mounted() 中声明的已分配this.property
【发布时间】:2020-07-21 22:20:48
【问题描述】:

我正在做一个项目,我正在使用 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 还很陌生,我不知道我在这方面做错了什么。如果有人能指出我做错了什么或者有更好的方法来做这件事,那将是非常有帮助的。

【问题讨论】:

  • 您正在使用 ansyc 调用来获取用户,因此 console.log 在 api 调用返回之前正在运行。链接另一个then 并在那里进行连接。
  • 这是因为 this.user 对象是异步更新的,并且依赖于等待 API 的响应:所以在不等待承诺解决的情况下将 this.user.id 记录到控制台当然会显示 @ 987654330@。之所以在模板中显示是因为一旦this.user 更新,VueJS 会重新渲染。
  • 你有竞争条件。您无需等待响应。 我使用它来连接频道 - 在 then 中执行此操作或使用 async/await,这是前者的语法糖。

标签: laravel vue.js laravel-echo laravel-broadcast


【解决方案1】:

问题是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);
    });
  }
}

【讨论】:

    猜你喜欢
    • 2019-10-11
    • 1970-01-01
    • 2021-02-12
    • 2019-06-02
    • 2019-06-21
    • 1970-01-01
    • 2018-07-17
    • 2018-05-22
    • 2018-11-26
    相关资源
    最近更新 更多