SoFunction
Updated on 2025-04-06

Optimize the sharing of a large number of conditional selection v-if in Vue template

Disadvantages of large number of v-ifs

In actual projects, you usually encounter scenarios where there are a large number of business conditions selection. In this case, if you use a large number of "v-if" and "v-else" instructions, it will cause

1. Page rendering performance decreases and loading time increases: eachv-if All of them need to traverse and calculate these conditions, especially when the condition selection is complex and the calculation overhead is high, which will increase the time-consuming of the initial rendering, thereby extending the loading time of the page.

2. Increased redundant code: too manyv-ifThis will make the template code verbose and difficult to maintain. This results in less readability of the code and is difficult to understand and debug.

3. Maintenance reduction: When there are a large number ofv-ifWhen, since each condition judgment is independent, modifying one of the conditions may require modification of multiple places, increasing the possibility of errors and complicating maintenance.

4. Memory increase: eachv-ifThe conditions will generate the corresponding DOM elements and are created and destroyed when switching the conditions. When there are a large number ofv-ifIt will increase memory usage and affect performance and resource consumption.

Optional optimization solution

Utilize computational properties

Transfer complex conditional logic to computed properties to process, avoiding frequent use of "v-if" and "v-else" in template templates. Control the rendered content by calculating the return value of the attribute, which makes the template code more concise, the logic of conditional processing is clearer and easier to maintain.

<template> 
    <div> 
        <span v-if="displayText">{{ displayText }}</span> 
    </div> 
 </template> 
 <script> 
     export default { 
         data() { 
             return { 
                 // ... 
              }; 
         }, 
         computed: { 
             displayText() { 
                 // Add complex conditional logic here                     if (/* condition */) { 
                        return 'Text 1'; 
                      } else if (/* another condition */) { 
                        return 'Text 2'; 
                      } else { 
                        return 'Default Text'; 
                       } 
               }, 
         },
     }; 
 </script>

Using asynchronous dynamic components (Dynamic components)

If different components are rendered according to the conditions, you can use<component :is="currentComponent">Dynamically switch components.

This optimization method combinesFactory modelTo use, register all component components in the factory components, know which component to produce according to the passed condition, and use :is for page rendering.

&lt;template&gt; 
    &lt;div&gt; 
        &lt;component :is="currentComponent"&gt;&lt;/component&gt; 
    &lt;/div&gt; 
&lt;/template&gt; 
&lt;script&gt; 
    import ComponentA from './'; 
    import ComponentB from './'; 
    import ComponentC from './'; 
    export default { 
        data() { 
            return { 
                // ... 
             }; 
         }, 
         computed: { 
             currentComponent() { 
                // Add complex conditional logic here                if (/* condition */) { 
                     return ComponentA; 
                 } else if (/* another condition */) { 
                     return ComponentB; 
                 } else { 
                     return ComponentC; 
                 } 
             }, 
        }, 
        components: { 
            ComponentA, 
            ComponentB, 
            ComponentC, 
         }, 
    }; 
  &lt;/script&gt;

Use v-show instead of v-if

You can use it when you need to frequently switch the display and hiding of elementsv-showAlternativev-if. becausev-showOnly the elements will be changeddisplayAttributes, avoid frequent switching of DOM elements to display and hide, andv-ifThe element will be completely removed or reinserted from the DOM, butv-showNot supported<template>Elements andv-else

&lt;template&gt;
    &lt;div&gt; 
        &lt;span v-show="isVisible"&gt;Show text&lt;/span&gt; 
    &lt;/div&gt; 
&lt;/template&gt; 
&lt;script&gt; 
    export default { 
        data() { 
            return { 
                isVisible: true, 
             }; 
         }, 
    }; 
&lt;/script&gt;

Move conditional logic into child components

Decomposing conditional logic into smaller subcomponents can make the code more modular and maintainable. Each child component can be responsible for handling its own conditional logic, thereby reducing the complexity of the parent component.

<!--  --> 
<template> 
    <div> 
        <child-component :data="data"></child-component> 
    </div> 
</template> 
<script> 
    import ChildComponent from './'; 
    export default { 
        components: { 
            ChildComponent, 
        }, 
        data() { 
            return { 
                data: /* some data */, 
             }; 
         }, 
    }; 
</script>   
<!--  --> 
<template> 
    <div> 
        <span v-if="condition1">Text 1</span> 
        <span v-else-if="condition2">Text 2</span> 
        <span v-else>Default Text</span> 
    </div> 
</template> 
<script> 
    export default { 
        props: ['data'], 
        computed: { 
            condition1() { 
                // Calculate condition1 based on  
            }, 
            condition2() { 
                // Calculate condition2 based on  
            }, 
        }, 
    }; 
</script>

Data preprocessing

If certain conditions remain unchanged during rendering, preprocessing can be done at the data level and the results are cached. This can avoid repeated calculation and judgment of conditions in the template.

&lt;template&gt;
  &lt;div&gt;
    &lt;template v-if="isConditionA"&gt;
      &lt;!-- Rendering conditions A Contents --&gt;
    &lt;/template&gt;
    &lt;template v-else-if="isConditionB"&gt;
      &lt;!-- Rendering conditions B Contents --&gt;
    &lt;/template&gt;
    &lt;template v-else&gt;
      &lt;!-- Render default content --&gt;
    &lt;/template&gt;
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
  data() {
    return {
      data: /* Raw data */,
      isConditionA: false,
      isConditionB: false
    };
  },
  created() {
    // Preprocess the data and calculate the conditional results    // You can process , and then calculate the value of , and ,  }
}
&lt;/script&gt;

The above is the detailed content of the solution to optimize v-if in Vue template. For more information on optimizing v-if in Vue template, please follow my other related articles!