lundi 4 septembre 2017

VueJs component: can't attribute axios reponse to a component variable

I am new to VueJs with Laravel. I have a component called Event in which a 'read more...' link shoud trigger a function that fetch the event infos from the data base and store the in a variable withing this same component.

Here is the code for my component:

<template>
<div class="container">
<div class="panel panel-default">
    <div class="panel-heading">
        <h5>
            Title: 
            <span class="pull-right">
                @click=getEventInfo(event.id)>Read more ...</a></span>
        </h5>
        <h5>publised by: 
             <span class="pull-right" v-text="timeFromNow(event.created_at)"></span>
        </h5>

    </div>

    <div class="panel-body">
        <p></p>
        </div>
    <div class="panel-footer">
            <p>
            <span>Event for: </span>
            <span>When:   at </span>
            </p>
    </div>
</div>
</div>
</template>


<script>
import moment from 'moment';
export default {
    name: 'app-event',
    props:['event'],
    data() {
        return {
           eventInfo: {}
        }
    },
    methods: {
        timeFromNow(tmp) {
            return moment(tmp).fromNow();
        },

        dayOfDate(d) {
            let dt = moment(d, "YYYY-MM-DD");
            return dt.format('dddd');
        },
        //event.id
        getEventInfo(id){  

            let url = 'events/' + id;

            axios.get(url)
            .then((response) => {
            console.log(response.data); //returns data
            this.eventInfo = response.data;
            console.log(this.eventInfo);//returns data
          });

          console.log(this.eventInfo); //returns nothing
        }
    }
}
</script>

The problem is when I click the 'read more...' link axios returns a response that I can check using console.log(response.data). Hovever when I console.log(this.eventInfo) outside the axios closure, it returns and ampty object.

Am I doing something wrong? Sorry if the question is too basic.

Thanks L.B



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire