Skip to content
Advertisement

For loop and strange Vue behaviour

I’m working on a project where I want to add some more input fields when clicking on a button.

So I tried jQuery.append but then there was a problem with v-model not being detected.

So I tried to achieve the same thing using Vue if-statement and I figured out it could be done much simpler by just adding objects to the variable deciding how many input fields listed in the first place.

But then I noticed something strange and I would like to know if this is by accident or if it’s meant to work this way.

So first of all – this is the html:

JavaScript

And this is the relevant Vue JS:

JavaScript

The thing is this is working fine. When I press the button to add an extra block it is inserted. But if I remove:

JavaScript

It’s not working.

Why is that relevant at all? It doesn’t matter what tag I use – it could be p instead of template and still the same result but it seems like the v-if statement is triggering some sort of rendering?

Could anyone please explain so I can understand better why this is happening?

** UPDATE **

I’ll narrow it down to avoid confusion:

JavaScript

Advertisement

Answer

Vue doesn’t notice this:

JavaScript

because it only notices array mutations made via array methods.

Having the reference to extraAddons in the loop lets Vue know that something has changed. If you use a mutator like

JavaScript

Vue should behave as expected without your needing to refer to extraAddons.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement