Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue: Waiting for props before mounted is run

Tags:

vue.js

I have component, ShopCart.vue (code below), that is receiving props from the parent. One of those props is cartItems. I am running a function on the cartItems in mounted() but to make sure the props were ready, I put them in Vue.nextTick, which I saw as a solution here on StackOverflow. That seemed to resolve the issue but I noticed it wasn't reliable and there were instances where the cartItems would be empty when the function was ready. To test this, I put them in a setTimeout for 3 seconds and then the cartItems had 20 passed items, so I know it's working..it's just running too quickly. How can I resolve this to ensure the props are ready in this component?

Part of the ShopCart.vue

export default {

data() {
    return {
        dataLoaded: false,
        modalType: null,
        orderNotes: null, 
        test: null,
        expireTimes: {

        }
    }
},
props: {
        cartItems:  {type: Array},
        cart:       {type: Object},
        customer:   {type: Object}
    },
mounted() {
    let vm = this;      

    Vue.nextTick(() => {
        vm.cartItems.forEach((item, index) => {
            Vue.set(vm.expireTimes, item.item_id, "")
            this.checkItemExpiry(item.expire_at, item.item_id)

        });
    });

}
like image 827
jjoan Avatar asked Dec 10 '22 03:12

jjoan


1 Answers

@Francisco Hanna's answer will work for you, but you can avoid a watcher (which is consuming resources) if you simply use v-if to render the shopCart component only after any cartItems exist:

in the parent component:

<shop-cart :cartItems="cartItems" v-if="cartItems.length"></shop-cart>
like image 198
Efrat Levitan Avatar answered Dec 15 '22 08:12

Efrat Levitan