Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hfalucas's avatar

Tips on Vue component behaviour isolation

Hello everyone! I would like to know your views/tips on how a Vue component should behave.

For the example let's use a simple scenario of posts. In the code block below we are looping through an array of posts, now let's say we want to delete one:

    <div v-for="post in posts>
        <post-item :post="post"></post-item>
    </div>

Should the PostItem.vue only emit an event and the request and removal from the array occur in the parent?

// PostItem.vue

export default {
    methods: {
        remove () {
            this$emit('delete:post', this.post)
        }
    }
}

Or its ok to make the request inside the component itself and then emit and event to the parent to remove the item from the array? If so how you guys deal with a possible request error to put it back on the array?

// PostItem.vue

export default {
    methods: {
        remove () {
            axios.delete(...)
            this.$emit('post:deleted', this.post)
        }
    }
}

Really looking forward to hear from you.

PS: No Vuex usage here :)

0 likes
3 replies
Sti3bas's avatar

@hfalucas I think either way is fine, but I would probably make a request in the parent component, so that all API requests (fetch posts, delete post) would be isolated in a single component.

If so how you guys deal with a possible request error to put it back on the array?

You would not be able to check if request has finished successfully, with the code above, because your component would be destroyed at this point. You would have to wait until request is finished and only then emit an event. So I guess making a request in parent component fits more in this case, as you can easily re-add deleted post if request fails.

1 like
hfalucas's avatar

@sti3bas if you make the request on the parent you can put it back if you send both the post and index on the event payload:

<post-item @remove:post="remove"></post>


// Parent component

methods: {
    remove ({post, index}) {
        this.posts.splice(index, 1) // removes the post

        axios.delete(...).catch(err => {
            this.posts.splice(index, 0, post) // if error put it back
        })
    }

}

I'm also thinking you are right, I should put the request on the parent as well. Thanks for your input :)

1 like

Please or to participate in this conversation.