【问题标题】:Fetch results undefined on first call [duplicate]在第一次调用时获取未定义的结果[重复]
【发布时间】:2021-05-23 21:59:18
【问题描述】:

我有以下 Vue 方法。单击编辑按钮时,会调用onEditUserPermissions。该函数还获取this.fetchUserPermissions。请求确实完成了,并且收到了响应。

methods:{
  onEditUserPermissions(item){
    this.userCheckbox = true
    let user = item.id
    this.selectedUser = item.id;
    
    this.fetchUserPermissions(user)
    for (let x of this.assignedUserPermissions){
      console.log('assigned',x.id)
      this.selectedUserItems.push(x.id)
    }
    
    this.editedIndex =  'users'
    this.dialog = true
  },
  fetchUserPermissions(user){
    this.$axios.get('/permissions/assigned/user/'+user)
    .then(res => {
      this.assignedUserPermissions = res.data
    })
  },
}

当我第一次单击时,for of 循环不起作用,它不会迭代,但是,当再次单击时,它会起作用。我可能离项目太近了,但谁能告诉我为什么?

【问题讨论】:

标签: javascript vue.js ecmascript-6 vue-component nuxt.js


【解决方案1】:

在尝试访问数据之前,您需要等待 http 承诺解决。它第二次起作用,因为它使用了第一次提取的结果。

首先,你需要从fetchUserPermissions返回promise,然后你需要在onEditUserPermissions等待那个promise:

methods: {
  async onEditUserPermissions(item){         // `async` keyword
    this.userCheckbox = true
    let user = item.id
    this.selectedUser = item.id;
    
    await this.fetchUserPermissions(user);   // awaiting the promise

    for (let x of this.assignedUserPermissions){
      console.log('assigned',x.id)
      this.selectedUserItems.push(x.id)
    }
    
    this.editedIndex = 'users';
    this.dialog = true    
  }

  fetchUserPermissions(user){
    return this.$axios.get('/permissions/assigned/user/'+user)  // return the promise
    .then(res => {
      this.assignedUserPermissions = res.data
    })
  },
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多