Using the @change, an alternative way to two way binding in vue

I recently started a role as a frontend engineer at Enyata, and the team I was added to uses vuejs and I being a react js developer, I had to just sit down and start learning and reading the documentation on the language. During my course of learning, I learnt about two way binding and how the v-model works to achieve this. One thing is that I was not just comfortable with how I had to have a declare a data property for every input tag. This is what I mean: firstImg.png

Tho, the method i am about to talk about isn't to bash vue js way of doing thing, as it's a framework and each framework has a way of doing it's own thing. I am simply bringing an alternative way. Any convention that works best for your team is what you should stick to. But knowing another way of doing things generally is pretty much an additional knowledge for you. I just think this method is shorter if you have a long form where you'll have to declare lots of data properties, hence one method handles everything.

That been said, on the image above, tho we only have two input tags, it might seems easier to just declare them in the data property but when you have multiple tags, it seems more like repetition to me, especially with my background from react, it looked like having multiple useState() for each input tags which is wrong performance wise, even if it gets the job done. I then thought about how I do I handle multiple tags without having to declare them in the data, here comes the use of "@ change" option readily available on each input tags.

Here is how I propose it should be done:

image2.png

Now, the image above has a form in the data property declared as null, each input tag has the " @ change " and a name which we would use to track which tag we are currently on. It's quite important that the name on each tag is unique. On the methods, you will see the handleFormChange function, it takes the previous state of the form, spreads it and adds it to the new object. That way, if we want to access any value we just need to call it how I did in the paragraph tag inside the template.

This is how it looks like in the console

console.png

So tell me what you think guys, is it worth trying?

NB: You can have the v-model working and declare the form as an object having each input name set as an empty string and it's accessed on the tag as " v-model="form.email" ".

0
Subscribe to my newsletter

Read articles from Oghenetega Philip directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Oghenetega Philip
Oghenetega Philip