首页 > 解决方案 > 道具对象的属性在刷新函数中未定义

问题描述

我使用 Vue.js 并且有一个组件。我将一个道具“请求”传递给该组件:

<adjustments-list
  v-if="request"
  :request="request"
/>

在组件中,我能够做到这一点:

<text-input
  :value="request.id"
/>

它的工作原理是显示“id”的值。

在组件的 props 部分:

props: {
  request: Object

在组件的挂载钩子中:

async mounted () {
  await this.refresh()
},

在组件的刷新功能中:

async refresh () {
  console.log('this.request.id =', this.request.id)
  if (this.request.id) {
    const data = await requestApi.getRequestResultAdjustmentByReqId(this.request.id)
  }
},

this.request.id 未定义。

我不确定为什么。

标签: vue.js

解决方案


如果该request属性对组件是异步可用的,那么您必须使用以下观察者的组合:

// adjustments-list component
new Vue({

  props: {
    request: Object
  },

  data() {
    return {
      apiData: null
    }
  },

  watch: {
    request(newValue, _oldValue) {
      this.refresh(newValue);
    }
  },

  mounted: function () {
    // Do something here
  },

  methods: {

    refresh (request) {
      if (request.id) {
        // Using promise instead of async-await
        requestApi.getRequestResultAdjustmentByReqId(request.id)
          .then(() => this.apiData = data);
      }
    }

  }
});

另外,请注意,mounted应该是一个普通的旧 JS 函数,而不是一个async函数。这是组件的生命周期方法,应该以特定方式运行。


推荐阅读