SoFunction
Updated on 2025-04-06

Implement calling functions in v-if of vue

vue v-if calling function

<div v-if="test()"></div>

The methods attribute is configured like this

methods: {
    test: function() {
        var result = false;
        // ...
        return result;
    }
}

Notes when using v-if

- No other elements can be added between if and v-else or v-else-if

The following is an error example

&lt;span v-if="type==1"&gt;Error demonstration&lt;/span&gt;
&lt;span&gt;Hahaha&lt;/span&gt;
&lt;p v-else&gt;Hehehe&lt;/p&gt;

The following is the correct example

&lt;span v-if="type==1"&gt;Correct demonstration&lt;/span&gt;
&lt;p v-else&gt;Hehehe&lt;/p&gt;
&lt;span&gt;Hahaha&lt;/span&gt;

-if is the same type of component

When displaying and hiding (or dom tree of the same template) it is best to add a key attribute to set a unique identifier on the outermost layer, otherwise problems will be easily caused by problems.

&lt;template v-if="type=== 'username'"&gt;  
  &lt;label&gt;username&lt;/label&gt;  
  &lt;input placeholder="Enter a username"&gt;  
&lt;/template&gt;  
&lt;template v-else&gt;  
  &lt;label&gt;Mail&lt;/label&gt;  
  &lt;input placeholder="Enter email"&gt;  
&lt;/template&gt;  

When switching the above code, only the placeholder is switched, and not re-rendered, because it uses the same template

If v-if switches to a control with complex logic, it is very easy to cause problems if it does not re-render during switching.

You need to add a key attribute to the control to be rerendered to uniquely identify the control. It will be rerendered after being identified by the key.

Examples are as follows:

&lt;template v-if="type=== 'username'" key="1"&gt;  
  &lt;label&gt;username&lt;/label&gt;  
  &lt;input placeholder="Enter a username"&gt;  
&lt;/template&gt;  
&lt;template v-else  key="2"&gt;  
  &lt;label&gt;Mail&lt;/label&gt;  
  &lt;input placeholder="Enter email"&gt;  
&lt;/template&gt; 

The above is personal experience. I hope you can give you a reference and I hope you can support me more.