First, the common ground of V-show and V-IF

We all know that v-show and V-if have the same effect in vUE (excluding V-else), controlling whether or not elements are displayed on the page

It’s the same in terms of usage

<Model v-show="Show" />
<Model v-if="Show" />
Copy the code
  • When the expression istrue“Takes up space on the page
  • When the expressions are bothfalse, will not occupy the page position

The difference between V-show and V-IF

  • Different means of control
  • Different compilation process
  • Different compilation conditions

Control: V-show hides by adding CSS to the element –display: None, the DOM element remains. V-if show hide is to add or remove the ENTIRE DOM element

Compilation process: The V-IF switch has a partial compile/uninstall process in which internal event listeners and subcomponents are destroyed and rebuilt as appropriate; V-show is simply a CSS-BASED switch

Compile conditions: V-if is true conditional rendering, which ensures that event listeners and subcomponents within the conditional block are properly destroyed and rebuilt during the switch. Only when the render condition is false, no action is done until it is true

  • v-show 由falseintotrueDoes not trigger the component’s life cycle
  • v-ifbyfalseintotrueWhen the component is triggeredbeforeCreate,create,beforeMount,mountedThe hook,trueintofalseWhen the component is triggeredbeforeDestory,destoryedmethods

Performance cost: V-IF has higher switching cost; V-show has a higher initial render cost;

## 3. V-show and V-IF principle analysis

The specific analysis process is not expanded here, and the general process is as follows

  • The templatetemplatetoastThe structure of theJSobject
  • withastTo get theJSObjects are assembledrenderandstaticRenderFnsfunction
  • renderandstaticRenderFnsAfter the function is called, the virtual is generatedVNODENode that contains the creationDOMInformation Required by nodes
  • vm.patchFunction through virtualDOMAlgorithm usingVNODENode creation TrueDOMnode

V – show principle

Elements are always rendered no matter what the initial conditions are, right

Let’s see how this is implemented in VUE

The code is easy to understand. If I have transition, I’ll do transition, and if I don’t, I’ll just set the display property


export const vShow: ObjectDirective<VShowElement> = {
  beforeMount(el, { value }, { transition }) {
    el._vod = el.style.display === 'none' ? '' : el.style.display
    if (transition && value) {
      transition.beforeEnter(el)
    } else {
      setDisplay(el, value)
    }
  },
  mounted(el, { value }, { transition }) {
    if (transition && value) {
      transition.enter(el)
    }
  },
  updated(el, { value, oldValue }, { transition }) {
    // ...
  },
  beforeUnmount(el, { value }) {
    setDisplay(el, value)
  }
}
Copy the code

V – if principle

V-if is much more complicated to implement than V-show, because there are also else else-if conditions to deal with, and here we only extract a small part of the source code dealing with V-if

Returns a node node, and the render function uses the value of the expression to determine whether to generate the DOM

export const transformIf = createStructuralDirectiveTransform(
  /^(if|else|else-if)$/,
  (node, dir, context) => {
    return processIf(node, dir, context, (ifNode, branch, isRoot) => {
      // ...
      return () => {
        if (isRoot) {
          ifNode.codegenNode = createCodegenNodeForBranch(
            branch,
            key,
            context
          ) as IfConditionalExpression
        } else {
          // attach this branch's codegen node to the v-if root.
          const parentCondition = getParentCondition(ifNode.codegenNode!)
          parentCondition.alternate = createCodegenNodeForBranch(
            branch,
            key + ifNode.branches.length - 1,
            context
          )
        }
      }
    })
  }
)
Copy the code

Use scenarios of V-show and V-IF

Both v-if and V-show control the display of DOM elements on the page

V-if is more expensive than V-show (directly manipulating DOM node additions and deletions)

If you need to switch very frequently, use V-show

It is better to use V-if if conditions rarely change at run time