Saturday, April 1, 2017

Using Laravel eloquent calculate total of like and passing into vue js file

Currently i am implementing a like system into my laravel project with Vue js. The scenario is after users liked the post. It will showing the total like of the post beside the like button. If using controller and passing data into view is easy to be done. But when change to Vue js i have no idea how to do it. This is my Like.vue file.

<template>

<button class="btn btn-primary" v-if="!auth_user_likes_post" @click="like()">
    Support
</button>

<button class="btn btn-primary" v-else @click="unlike()">
    Unsupport
</button>

export default {
    mounted(){

    },

    props: ['id'],

    computed: {
        likers() {
            var likers = []

            this.post.likes.forEach( (like) => {
                likers.push(like.user.id)
            })
            return likers
        },
        auth_user_likes_post() {
            var check_index = this.likers.indexOf(
                this.$store.state.auth_user.id
            )
            if (check_index === -1)
                return false
            else
                return true
        },
        post() {
            return this.$store.state.posts.find( (post) => {
                return post.id === this.id
            })
        }
    },
    methods: {
        like() {
            this.$http.get('/like/' + this.id)
                .then( (resp) => {
                    this.$store.commit('update_post_likes', {
                        id: this.id,
                        like: resp.body
                    })

                })
        },
        unlike() {
            this.$http.get('/unlike/' + this.id)
                .then( (response) => {
                    this.$store.commit('unlike_post', {
                        post_id: this.id,
                        like_id: response.body
                    })
                })
        }
    }
}

The like and unlike functions has been done and working perfectly. Now i just need to show the total number.

This is Feed.vue file. The like was adding to this page.

<div class="post-description">
                    <p></p>
                    <div class="stats">
                        <like :id="post.id"></like>
                        <a href="#" class="stat-item">
                            <i class="fa fa-retweet icon"></i>12
                        </a>
                        <a href="#" class="stat-item">
                            <i class="fa fa-comments-o icon"></i>3
                        </a>
                    </div>
                </div>

If my function cannot be achieved the expected scenario then can you recommend other ways which can do that?



via masterhunter

Advertisement