ZetecVan
2 years ago
37
0
Vue

Component Within A Component Props

Posted 2 years ago by ZetecVan

I have created a 'like' component, which is passed a prop of the id of the thing being liked, and whether it is currently liked. It works when it's stand alone, but when I put it within another component, it doesn't work out whether it's already liked. Here's the code for the component.

        <favorite
            :post={{ $post->id }}
            :favorited={{ $post->favorited() ? 'true' : 'false' }}
        ></favorite>

I think my issue is that the parent component does an axios call to an internal api, and that returns whether it's liked or not (amongst other things). I put a console.log in the child components mounted method to output the value of 'favorited' prop, and it returns undefined, however, looking at that same prop in Chrome Vue Tools, it's populated properly.

<script>
    export default {
        props: ['post', 'favorited'],

        data: function() {
            return {
                isFavorited: '',
            }
        },

        mounted() {
               console.log(this.favorited)        // Returns undefined
           this.isFavorited = this.isFavorite ? true : false;
        },

        computed: {
            isFavorite() {
                return this.favorited;
            },
        },

        methods: {
            favorite(post) {
                axios.post('/favorite/'+post)
                    .then(response => this.isFavorited = true)
                    .catch(response => console.log(response.data));
            },

            unFavorite(post) {
                axios.post('/unfavorite/'+post)
                    .then(response => this.isFavorited = false)
                    .catch(response => console.log(response.data));
            }
        }
    }
</script>

It's as if the component is mounted, before the parent component is fully loaded. Does anyone know how to solve this?

Please sign in or create an account to participate in this conversation.