Phillis Peters Phillis Peters - 1 year ago 324
Javascript Question

How to call a vue.js function on page load

I have a function that helps filter data. I am using

when a user changes the selection but I also need the function to be called even before the user selects the data. I have done the same with
previously using
but I understand that there is no such a directive in

This is my function:

getUnits: function () {
var input = {block: this.block, floor: this.floor, unit_type: this.unit_type, status: this.status};

this.$'/admin/units', input).then(function (response) {
this.units =;
}, function (response) {

In the
file I use blade forms to perform the filters:

<div class="large-2 columns">
{!! Form::select('floor', $floors,null, ['class'=>'form-control', 'placeholder'=>'All Floors', 'v-model'=>'floor', 'v-on:change'=>'getUnits()' ]) !!}
<div class="large-3 columns">
{!! Form::select('unit_type', $unit_types,null, ['class'=>'form-control', 'placeholder'=>'All Unit Types', 'v-model'=>'unit_type', 'v-on:change'=>'getUnits()' ]) !!}

This works fine when I select a specific item. Then if I click on all lets say
all floors
, it works. What I need is when the page is loaded, it calls the
method which will perform the
with empty input. In the backend I have handled the request in a way that if the input is empty it will give all the data.

How can I do this in

My Code:

Answer Source

You can call this function in beforeMount section of a Vue component: like following:

     getUnits: function() {...}

Working fiddle:

There are different lifecycle hooks Vue provide:

I have listed few are :

  1. beforeCreate: Called synchronously after the instance has just been initialized, before data observation and event/watcher setup.
  2. created: Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.
  3. beforeMount: Called right before the mounting begins: the render function is about to be called for the first time.
  4. mounted: Called after the instance has just been mounted where el is replaced by the newly created vm.$el.
  5. beforeUpdate: Called when the data changes, before the virtual DOM is re-rendered and patched.
  6. updated: Called after a data change causes the virtual DOM to be re-rendered and patched.

You can have a look at complete list here.

You can choose which hook is most suitable to you and hook it to call you function like the sample code provided above.