Use cases, Vue.js

Vue.js use case #2 – dynamic v-model

Part of my work is B2B custom e-commerce. And, of course, on many occasions, a custom order process is needed.

Recently, the job was to make a grid, so that the user could easily insert quantities for several combinations of size and color. Not very original, but, I suppose, a useful practical example of a B2B situation.

The data to build the grid is loaded from an api, but here we will just hard-coded it. And, also, make other simplifications.

A starting point for the code might be:

We can see the result:

In this example, we have three sizes and three colors, but because data is dynamic we must face a more general case.

Now, the aim is to use effectively the set of inputs, which means getting data from the inputs but also insert data in the inputs, because the grid must allow showing an already saved order. In these cases, v-model can be a good way to go.

For that, it is useful to have some data structure. We will use an array of objects. Each object will have three properties: a “row”, for the size, a “column”, for the color, end a “value”, for the quantity. May the “mounted” hook is a good place to fill this array:

Next step is to bind the inputs to their respective object. But, remember, we must be generic. So, a first thought is just to use a method in v-model that returns a different variable for each input. But… v-model doesn’t accept a method!

Let’s jump for the full code:

Which give us this:


To achieve this result the most important technique was the way to write the v-model:

v-model=grid[getCellIndex(size, color)].value

and its associated method:

getCellIndex(row, column) {
     return this.grid.findIndex(c => c.row == row && c.column == column);

For me, is was a discovery!

Leave your thought here