Access prop in Vuejs method

Asked

Viewed 366 times

1

I’m passing a array of objects to a component and within this component I try to access past values:

<orders-list :orders="items"></orders-list>

Component orders-list:

<template>
  <div>
    <b-form-select
      v-model="filterChannel"
      :options="Array.from(
        new Set(
          orders.map(item => item.channel)
        )
      )"></b-form-select>
  </div>
</template>

<script>
    export default {
        props: ['orders'],
        ...
        created(){ console.log(this.orders); } // null
    }
</script>

within the template I can render all the information but the console always sends me an error saying that it cannot access the method map of null even rendering the items... Already inside the method is displayed null, but if I only use console.log(this) I can visualize the orders with all requests within.

How can I access a prop within the methods of a component?

  • Are you receiving these Orders (items) as? With an ajax request?

  • @Miguel, yes the orders come from the component pai of orders-list

1 answer

0


Access a prop exactly as you’re doing, this.orders, ex:

...
methods: {
    get_orders: function() {
        return this.orders;
    }
},
...

As per comment I realized that these items came from an ajax request, which is asynchronous and has not yet been completed when rendering the component, I would say that the right solution will be:

<template>
  <div>
    <b-form-select v-if="orders != null"
      v-model="filterChannel"
      :options="Array.from(
        new Set(
          orders.map(item => item.channel)
        )
      )"></b-form-select>
  </div>
</template>

<script>
    export default {
        props: ['orders'],
        ...
        created(){ console.log(this.orders); } // null
    }
</script>

Note that I added v-if="orders != null" so that this element (b-form-select) only be rendered when orders cease to be null.

DOCS

You can also start items as being an empty array and so do not put the condition I proposed on top, in the parent component can:

<template>
    ...
    <orders-list :orders="items"></orders-list>
    ...
</template>

<script>
    export default {
        data() {
            return {
                items: [],
            }
        },
        ...
    }
</script>
  • even after the component mounting if I try to access the prop by a watcher receive Undefined;

  • But yesterday was null right? @RFL, this problem has nothing to do with the same I think

  • 1

    I’ll open another question.

  • OK @RFL, I’ll see if I can help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.