使用 EventBus 传递用户 ID 来调用 API 但不会将响应绑定到输入字段

Using EventBus to pass userID to call API but will not bind response to input field

我使用 EventBus 将 UserId 传递给另一个组件 (UpdateStaff)。然后,我想在 url/api/staffs/{UserId} 调用 API 以获取该特定用户的数据并将数据绑定到输入字段。我能够获取响应负载但无法绑定到输入字段。

UpdateStaff.vue:

模板中的输入字段示例:

<input class="input" type="text" placeholder="Username" v-model="data.username">

数据属性和创建方法:

data () {
  return {
    data: {
      name: '',
      username: ''
    }
  }
},
created () {
  EventBus.$on('getUserId', (userId) => {
    axios.get(staffUrl + '/' + userId)
      .then((response) => {
        let self = this
        self.data.username = response.data.username
        self.data.name = response.data.name

        console.log(self.data.username)
        // It prints out exactly what i want
        // BUT it doesn't show the data in the input field....?
      })
      .catch((error) => {
        console.log(error)
      })
  })
}

Staff.vue:

里面有一个 vuetable 组件来显示所有员工。单击更新按钮后,我通过调用 onActions 方法重定向到 UpdateStaff 页面。

methods: {
  onActions (action, data) {
    router.push({ path: '/user/UpdateStaff' })
    EventBus.$emit('getUserId', action.data.userId)
  }
}

以前,我可以单独使用 axios 在输入字段中显示数据。但是,在添加 EventBusaxios 之后,我无法再在输入字段中显示数据。

我应该如何解决这个问题?

您没有正确看到数据更新的原因是,当您在 .then 回调中引用它时,this 不是 Vue 实例。

let self = this 语句放在 created 挂钩的最开头,以确保您存储了对 this:

的正确引用
created () {
  let self = this
  // after this point, `self` will reference the Vue instance even in callbacks

  EventBus.$on('getUserId', (userId) => {
    axios.get(staffUrl + '/' + userId)
      .then((response) => {
        // setting `self` to `this` here doesn't make sense because `this` 
        // is not refering to the Vue instance in this callback

        self.data.username = response.data.username
        self.data.name = response.data.name
      })
      .catch((error) => {
        console.log(error)
      })
  })
}

当您推送到该路由时未处理 getUserId 事件的原因是 $emit 事件在创建 UpdateStaff 组件之前被触发(意味着$on 处理程序尚未设置)。

要等待组件创建,请将 $emit 包装在 this.$nextTick 回调中:

methods: {
  onActions (action, data) {
    router.push({ path: '/user/UpdateStaff' })
    this.$nextTick(() => {
      EventBus.$emit('getUserId', action.data.userId)
    })
  }
}

来自the documentation关于Vue.nextTick的用法:

Defer the callback to be executed after the next DOM update cycle. Use it immediately after you’ve changed some data to wait for the DOM update.