29

hey I'm pretty new to Vue.js and I'm trying to accomplish what seems to be a simple thing but I'm, having trouble. Essentially, I need it so every time a component is loaded into the DOM, one of it's methods fire. Here is my current code, I've tried to use v-on:load but it doesn't seem to work.

Vue.component('graph', {
    props:['graphId','graphData'],
    template: '<canvas v-on:load="{{populateGraph()}}"></canvas>',
    methods: {
        initGraph: function () {
            var settlementBalanceBarChart = new Chart(this.graphId, {
                type: "bar",
                data: settlementBalanceBarData,
                options: settlementBalanceBarOptions
            });
        },
        //this is the function I would like to run
        populateGraph: function () {
            alert('{{graphId}}');
        }
    }

});

var vm = new Vue({
    el: "#app",
    mounted: function(){

    }

});

The same code functions fine if I use the v-on:click event

2 Answers 2

32

There are instance lifecycle hooks that you can use for that. For example:

Vue.component('graph', {
    props:['graphId','graphData'],
    template: '<canvas></canvas>',
    created: function () {
        alert('{{graphId}}');
    },
    methods: {}
});
Sign up to request clarification or add additional context in comments.

1 Comment

does created() run one time after render completed?
5

You have to call the function prefixed by "this" as following:

var data =
{
   cashiers: []
}

var vm = new Vue({
    el: '#app',
    data: data,
    created: function () {
       this.getCashiers();
    },
    methods: {
         getCashiers: function () {
          vm.cashiers = [];
         }
    }

});

3 Comments

Any reason why you write the getCashiers function in the methods declaration and not in the created declaration?
"methods declarations" is the right place for writing the methods. "created declarations" is the place where you can call methods after the component is completely created.
@kaleidawave Even though in this case it may seem useless, creating it inside methods is a good practice, useful for example when you need to call that same method on creation and on other events.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.