Konrad Viltersten
Konrad Viltersten

Reputation: 39118

How to implement a function when a component is created in Vue?

According to the docs, the constructor of the Vue object is managed like this.

var vm = new Vue({
  created: function () { console.log("I'm created!"); }
});

However, I can't figure out how to do the corresponding thing when a Vue component is created. I've tried the following but don't get any print to the console.

export default {
  created: function() { console.log("Component created!"); }
}

Is it possible to subscribe/listen to a component being rendered? I'd like to react to that event by downloading some data and putting it in the store, so that the table that the component carries will get its information to display.

Upvotes: 6

Views: 14583

Answers (2)

Milan MiNo Michalec
Milan MiNo Michalec

Reputation: 155

components doesn't have life cycle hooks like app. but they has something similar. that fixed my problem: https://v2.vuejs.org/v2/api/#updated

Upvotes: 1

Sankalp Singha
Sankalp Singha

Reputation: 4546

In my applications, I tend to use the mounted hook to load up some Ajax data once the component has mounted.

Example code from my app:

Vue.component('book-class', {
    template: '#booking-template',
    props: ['teacherid'],
    data: function () {
        return{
            // few data items returned here..
            message: ''
        }
    },
    methods: {
        // Few methods here..
    },
    computed: {
      // few computed methods here...
    },
    mounted: function () {


        var that = this;
        $.ajax({
            type: 'GET',
            url: '/classinfo/' + this.teacherid,
            success: function (data) {
                console.log(JSON.stringify(data));

            }
        })
    }
});


new Vue({
    el: '#mainapp',
    data: {
        message: 'some message here..'
    }
});

However, I can also use created() hook as well as it is in the lifecycle as well.

In Vue2 you have the following lifecycle hooks:

enter image description here

Upvotes: 8

Related Questions