I have a function that helps filter data. I am using v-on:change
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 AngularJS
previously using ng-init
but I understand that there is no such a directive in vue.js
This is my function:
getUnits: function () {
var input = {block: this.block, floor: this.floor, unit_type: this.unit_type, status: this.status};
this.$http.post('/admin/units', input).then(function (response) {
console.log(response.data);
this.units = response.data;
}, function (response) {
console.log(response)
});
}
In the blade
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>
<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()' ]) !!}
</div>
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 getUnits
method which will perform the $http.post
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 vuejs2
?
My Code: http://jsfiddle.net/q83bnLrx
You can call this function in beforeMount section of a Vue component: like following:
Working fiddle: https://jsfiddle.net/q83bnLrx/1/
There are different lifecycle hooks Vue provide:
I have listed few are :
vm.$el
.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.
You need to do something like this (If you want to call the method on page load):
you can also do this using
mounted
https://vuejs.org/v2/guide/migration.html#ready-replaced