1
votes

I have a vue-nuxt component and want to initially set the data-(property) of my component with the data which I loaded by an asyncData API call.

data () {
  return {
    selected_company: this.contracts.company1.id *--> this gives me an undefined value*
  }
},
async asyncData({ app }) {
  const contracts = await app.$axios.$get("/companies/contracts")
return {contracts}

In my template I am able to access the data with the following code (therefore the data is successfully loaded):

{{this.contracts.company1}}

Since I have multiple entries in "contracts" I want to display them (e.g. in a dropdown) and capture the selected company with v-model. For some reasons I need to set an initial value for my "selected_company"-attribute. This is a simplified example (my data structure is more complex and consists for example of nested elements).

How can I set an initial value for the data-properties e.g "selected_company" based on the result of a asyncData-call? Do I miss something important or is there no easy-way for that?

Any help is highly appreciated! thank you in advance

1

1 Answers

2
votes

Instead of doing the initial value inside the data property, you can try to add it in the created method.

created () {
  this.selected_company = this.contracts.company1.id
}

Or if it still doesn't work, try to add it to your watch property.

watch: {
  contracts: {
    handler (val) {
       this.selected_company = val.company1.id
    },
    deep: true
  }
}