Writing a Custom Conditional Vue Directive
Just another fancy post title.
The task
There is a modal component on the page I’m currently working on. The modal contains a set of textfields which are generated using v-for
over the fields
property to keep it dynamic. When toggling the modal the first textfield should be focused automatically.
The first, very trivial, solution I tried was to set the input to autofocus if the textfield’s index equals 0. It looked like the following snippet:
<div v-for="(field, index) in fields">
<input type="text" v-if="index === 0" autofocus>
<input type="text" v-else>
</div>
This “solution” actually kind of worked, but only on the initial page load. If I were to open, close & reopen the modal the focus would not be set.
The final solution
The solution I finally came up with is in my opinion pretty cool & flexible. Basically I wrote a custom directive named v-focus
which set’s the element it is set on focused, only if the passed expression evaluates to true. This allows me to shorten the above snippet to this simple one-liner:
<input type="text" v-for="(field, key) in fields" v-focus="key === 0">
I think for this example the code says more than thousand words, so here it is 😊
Please feel free to give me your feedback for the final solution & fork it on JSFiddle.
To finally wrap up this post I just want to point out how much I like VueJS & it’s new, but simple and powerful, ecosystem incl. VueRouter & VueX.
Have a nice day / night & happy coding! ✌🏻