[Vuejs]-How can I run condition in vue component before run html in the template?

0👍

Technicaly the beforeUpdate hook can be used for that. Have a look at it:
https://v2.vuejs.org/v2/api/#beforeUpdate

0👍

First of all, you are accessing an array in your template as an object. So, if it’s an array, use a v-for to loop over the order array and then access it. But I don’t think you would want a for loop in the header. So expose a computed property that returns the appropriate element of your order array and use that in the template.

The second point, your error message. According to the Vue Instance Life Cycle Hooks, the template is loaded after data is ready. But in your case, the watcher is firing after the template loads. So you are getting undefined error. There are 2 things you can do:

1: Have a loader displayed until your watcher fires and your order array has the appropriate data. Then you can use a method to get the element from the ‘orderDetails’ array.

<template>
<div id="modal-transaction" class="modal fade" tabindex="-1" role="dialog">
    ...           
        <div v-if="orderNumber" class="modal-header">
            <h4 class="modal-title">{{orderNumber}}</h4>
        </div>
        <!-- have some loader -->
        <div v-else class="loader" ></div>
    ...
</div>
</template>

<script>
export default {
    ...
    data() {
        return {
            order: [],
            orderNumber: null
        }
    },
    watch: {
        orderDetail: {
            handler() {
                this.order = this.orderDetail;                   
                this.orderNumber = this.getOrderNumber();
            },
            immediate: true
        }
    },
    methods: {
      getOrderNumber() {
        //process this.orderDetail to get the appropriate orderNumber
      }
    }
</script>

2: If possible, have the ‘orderDetails’ array ready before you trigger the modal.

Leave a comment