I’m starting a series on Vue.js uses cases. This first post is about interconnected data and selections boxes.
Just yesterday I was working on a project with a use case which, being fairly normal, made me think for a while. The project is a B2B custom platform. I had this data structure:
- a list of product categories
- a list of subcategories for each category
- a list of products for each subcategory
- a list of related products for each product
This data is interconnected in a clear way: we start with the first list and select an item (a category); then, we have a second list, dependent on that chosen category; we now choose an item from the second list (a subcategory); and, again, we have a third list (of products) dependent on chosen subcategory… etc! We see the point. We have something like a domino effect.
From the UI perspective, each of the first three lists is a selection box. The fourth list doesn’t matter for the case: we can think that it’s just shown on the screen.
When the user starts the interact with the form, I wanted to fill all selection boxes with predefined options: just the first item on the list.
I wandered for while about the best way to make this component, the main goal being, of course, to have a reactive form with the cleanest code possible.
The idea is that the same code works for the first use of the form (the one with the defaults selections) and for the next steps (the ones where the user is playing with the selection boxes).
In the end, the way to go was to depend on data and watchers.
To inspect the code, let us start with only the first selection box.
Probably, there isn’t much in this starting point that is new to you. When instantiating the component, in the “mounted” hook, we get the categories data. In the real case, of course, at this moment I use an api, but here we just call a method, to simplify. We also have a variable, “activeCategory”, that is the model of the selection box. This way, every time the selection changes, the variable also changes. Finally, we are watching changes in “activeCategory” and, for now, just console logging the new value.
The next step is to solve the domino effect. When “activeCategory” changes, we want all the are relevant data to be called from the api (here we call methods, to make it easier) and set the selections boxes.
Let’s see the final code:
It is perhaps a little verbose code, but we get the idea.
Every time we select a value, all the chain updates. And it works also for the first time load. That was the main goal. The approach was to use watchers and, within each watcher, call the next method. Clean, no?