v-show/v-if usage scenarios and differences

  1. v-if: It is a true conditional rendering, when the condition is false, the element will not be rendered into the DOM. It dynamically adds and removes elements according to conditions, so it has a process of rendering and unloading.
  2. v-show: It is a simple conditional display, when the condition is false, the element will be added a display: none CSS style, thus hiding the element. It doesn't have to render and unload, so it performs better.
Same point:

​ All dynamically display hidden components

difference:
  1. V-show hiding is a means of CSS. Add display:none to the element, and the dom element is still on the DOM tree.

​ v-if hiding is to add or delete the dom element as a whole, and it will be removed from the DOM tree.

  1. The switching overhead of v-show is small, but there will be an overhead for initial rendering, which is suitable for scenes with frequent switching.

  2. The switching overhead of v-if is high. If the initial condition is false, there is no need to render for the first time. When switching infrequently or even not switching, it is recommended to use v-if

  3. When v-if changes from false to true, it will trigger the beforeCreate, create, beforeMount, mounted hooks of the uninstalled component, and when it changes from true to false, it will trigger the beforeDestory and destroy methods of the component; v-show will not trigger the hidden Any lifecycle hooks for the component.

  4. A pitfall and attention point ( encountered in development ): v-show is invalid when used on template, but v-if is valid.

for example:

For example, when we need to show a modal box when the user clicks a button

<template>
  <div>
    <button @click="showModal = true">Show Modal </button>
    <div v-if="showModal" class="modal">
      Modal Content
    </div>
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      showModal: false
    };
  }
};
</script>

In this example, when showModalis true, the modal box will be rendered, otherwise it will not be rendered. Since the modal will not be rendered when not shown, using v-ifcan improve the performance of the application.

Guess you like

Origin blog.csdn.net/m0_61696809/article/details/129351686