Simple inline editable fields with Vue.js

In this tutorial, I will show you how to create simple dynamically editable fields in your Vue application. For the purpose of this tutorial I’m going to use Vue 2 but the same principles apply to Vue 3 as well.

For the sake of simplicity I will first share the code and then add someexplanations below:

Main functionality

Let’s begin with the state. We have 2 values- fields and editedFieldId. The fields array contains all the field objects through which we iterate and the editedFieldId represents the id of the currently edited element. Depending on editedFieldId‘s value we weither display the field as a text or as an input. The function toggleEdit handles the buttons click and sets the editedFieldId to the provided id or sets it to null none is provided.

Autofocus the editable field

I assume that it’s easy to understand how editedFieldId is set in the function. However, you probably wonder why we use this.$nextTick and refs here. As in most web applications, we want the currently edited field to be automatically focused. Unfortunately, adding the “autofocus” attribute to the input element does not work due to the dynamic appearance of our input fields. The easiest alternative is to access the DOM element and set the focus programatically using the focus() function. However, we need to wrap this inside this.$nextTick callback, because of the asyncronous nature of JavaScript. Esentially, we use this.$nextTick to ensure that its callback is executed after the other asyncronous operations(in our case the state change and the display of the input field). If we don’t use it, then our input won’t be focused because we are trying to access the element before it has become visible. You can learn more about under this link.

Here is the code in action:

Inline editable fields in action

Enjoy!