[Vuejs]-Vue js and favorite/like button

1👍

If the server sends back a successful response you can increment the number that is already there.

This initial number is something you have gotten either through a prop, directly from the server or through an initial AJAX request.

If you want to “permanently” update the amount of likes on your button you have to persist it to a database(or some other storage medium). On you server you could have a route that accepts a post id as an argument and increment that specific user post:

/incrementlike/243

That is where you would make a POST ajax request to. Most of the time in an MVC framework you would have a controller action/method mapped to this route that holds the logic to respond to this call.

If you are interested in the part that happens after you make an AJAX request to the server to increment your like on the backend side, I suggest you read up on routing or MVC structure.

1👍

How you would do this is really done on a case by case basis. It really depends on a number of things, for example what your backend does to a post when it is liked.

If you would like a general ‘explanation’ to the process I attach it below, this is not really Vue specific, but the general idea is the same:

Frontend side:

  • Modify the local state of you post to set the proper flag, ex. post1.liked = true immediately when it is clicked, before sending the request to the server.
  • Make sure your GUI represent this change. ex. Base the color of the button on the property ‘liked’ of each post.
  • If a failure response it received from the server, notify the user and allow them to ‘try again’ or something similar.
  • When refreshing the page, make sure changes are fetched from the server, If you have done the backend part correctly, the modification of the state of the post will be correct in the data you receive from your backend (post1.liked will be true)

Backend side

When the request comes in, modify the state of the post the correct way and make sure that next time the post is fetched, the new state is sent.

Leave a comment