Search code examples
vue.jsvuejs2vuex

Vue/Vuex Accessing Objects elements


Hi I am getting confused as to how I can access some data within my Object. I am using Vuex and I have a standard page. Here, I use a getter to obtain the Payment Object and pass it to a component.

<template>
    <div>
        <div class="container">
            <div class="row">
                <div class="col-12 flex">
                    <payment-details :payment="payment"></payment-details>
                </div>
            </div>
        </div>
    </div>
</template>

<script>

    import {
        PaymentDetails
    } from "@/components/Payment";

    export default {
        components: {
            'payment-details': PaymentDetails
        },
        created () {
            if (!this.payment.paymentID) {
                this.$store.dispatch('paymentById', this.$route.params['id'])
            }
        },
        computed: {
            payment () {
                return this.$store.getters.paymentById(this.$route.params['id'])
            }
        }
    }
</script>

Now within the component, within the template, I can do something like this

<template>
    <div v-if="payment">
        <div class="row">
            <div class="col-12">
                <h3 class="h-100">{{ payment.details }}</h3>
            </div>
        </div>
    </div>
</template>

This all works fine. However, within this component, I need to access some elements of the payment object. This is where I get confused, if I create a mounted or created hook and do this

created() {
    console.log(this.payment)
}

I always get an Observer object. If I try accessing an element from this Object e.g.

created() {
    console.log(this.payment.details)
}

I get undefined. I basically have a slideshow I am creating in a mounted hook. I need to push some items contained within this Object onto the slideshow array.

So how can I actually get access to the elements of this Object?

Thanks


Solution

  • You should use watcher on your vuex object.

    Here is link to documentation https://v2.vuejs.org/v2/guide/computed.html#Computed-vs-Watched-Property

    Most probably your this.payment.details is instantiated after your created method was called.

    Move your code from created method to:

    export default {
        watch: {
          payment: function (val) {
            console.log('-------- this is this.payment.details:');
            console.log(val.details);
          },
        ...