异步/等待无法在Vue.js中正常工作

时间:2019-07-18 19:50:13

标签: javascript vue.js async-await

我似乎无法在Vue JS应用程序中使异步/等待正常工作。我在“创建的”生命周期钩子中将其触发,但是当我在“ beforeMount”生命周期钩子中console.log注销结果时,我得到的是空值。

我需要在加载DOM之前先填充变量 holidays holidaysMap ,但似乎无法做到这一点。

async beforeCreate() {
    try {
        this.holidays = await axios({
        method: 'post',
        url: 'https://controlapi.totalprocessing.com/api/get-holiday',
        data: { userId: localStorage.user_id },
        config: { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}
        })
        .then(response => {
            return response.data;
        })
        .catch(e => {
            this.errors.push(e)
        })

        this.holidays.forEach(e => (this.holidaysMap[e.date] = this.holidaysMap[e.date] || []).push(e));
        console.log(this.holidaysMap);
    }
    catch(e) {
        console.log(e)
    }
},
beforeMount() {
    console.log(this.holidays);
}

enter image description here

<v-calendar ref="calendar" v-model="today" @click:date="dayClick" :value="today" :end="end" :weekdays="weekdays" :locale="locale" :type="type" :short-months="false" color="primary">
    <template v-slot:day="{ date }">
        <template v-for="holiday in holidaysMap[date]">
            <v-menu :key="holiday.first_name" v-model="holiday.open" full-width offset-x>
                <template v-slot:activator="{ on }">
                    <div v-if="!holiday.time" :class="{ 'half-day-1' : holiday.half_day == 'AM', 'half-day-2' : holiday.half_day == 'PM' }" v-ripple class="event" v-on="on" v-html="holiday.first_name"></div>
                </template>
                <v-card color="white" min-width="350px" flat>
                    <v-toolbar color="primary" dark>
                        <v-toolbar-title v-html="holiday.first_name"></v-toolbar-title>
                    </v-toolbar>
                    <v-card-title primary-title>
                        <div class="holiday-details-container">
                            <span class="holiday-details-title">Date:</span><span class="holiday-details">{{ holiday.date }}</span><br>

                            <span class="holiday-details-title">Description:</span><span class="holiday-details">{{ holiday.description }}</span><br>

                            <span v-if="holiday.half_day" class="holiday-details-title">Half Day:</span>
                            <span v-if="holiday.half_day == 'AM'" class="holiday-details">Morning</span>
                            <span v-if="holiday.half_day == 'PM'" class="holiday-details">Afternoon</span><br>
                        </div>         
                    </v-card-title>
                    <v-card-actions>
                        <v-spacer></v-spacer>
                        <v-btn color="error">Delete</v-btn>
                        <v-btn color="primary">Ok</v-btn>
                    </v-card-actions>
                </v-card>
            </v-menu>
        </template>
    </template>
</v-calendar>

0 个答案:

没有答案