Pathros Pathros - 1 month ago 45
Ajax Question

Vue js Ready function is not triggered

I have this vue function where there are basically two methods. The first one

postStatus
is used to save a post just after the user clicks on the save button, and the other one
getPosts
is used to retrieve all previous posts of that user from the database.

Here is the vue.js, where there is an ajax call to a controller (in Laravel 5.3)

$(document).ready(function () {

var csrf_token = $('meta[name="csrf-token"]').attr('content');
/*Event handling within vue*/
//when we actually submit the form, we want to catch the action
new Vue({
el : '#timeline',
data : {
post : '',
posts : [],
token : csrf_token,
limit : 20,
},
methods : {
postStatus : function (e) {
e.preventDefault();
//console.log('Posted: '+this.post+ '. Token: '+this.token);
var request = $.ajax({
url : '/posts',
method : "POST",
dataType : 'json',
data : {
'body' : this.post,
'_token': this.token,
}
}).done(function (data) {
//console.log('Data saved successfully. Response: '+data);
this.post = '';
this.posts.unshift(data); //Push it to the top of the array and pass the data that we get back
}.bind(this));/*http://stackoverflow.com/a/26479602/1883256 and http://stackoverflow.com/a/39945594/1883256 */

/*request.done(function( msg ) {
console.log('The tweet has been saved: '+msg+'. Outside ...');
//$( "#log" ).html( msg );
});*/

request.fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
},
getPosts : function () {
//Ajax request to retrieve all posts
$.ajax({
url : '/posts',
method : "GET",
dataType : 'json',
data : {
limit : this.limit,
}

}).done(function (data) {
this.posts = data.posts;
}.bind(this));

}
},
//the following will be run when everything is booted up
ready : function () {
console.log('Attempting to get the previous posts ...');
this.getPosts();
}
});

});


So far the, first method
postStatus
is working fine.

The second one is supposed to be called or fired right at the ready function, however, nothing happens. I don't even get the console.log message
Attempting to get the previous posts ...
. It seems it's never fired.

What is the issue? How do I fix it?

Notes: I am using jQuery 3.1.1, Vue.js 2.0.1

Answer

I see that you are using Vue 2.0.1. There is no ready method in Vue 2.0 and above.

Here is the link to list of all Vue 2.0 changes: https://github.com/vuejs/vue/issues/2873

As mentioned in the page above, you can use mounted instead of ready.

Not an issue, but just a note: You are mixing jQuery and Vue extensively. If you need jQuery only for http related functions, you may instead use vue-resource - https://github.com/vuejs/vue-resource

Comments