Vue skills revealed: The difference and performance comparison between v-show and v-if are clear at a glance

Jiangcheng Cheerful Pea: Personal homepage

Personal column :《VUE》《javaScript》

Personal website : “Jiangcheng Cheerful Pea”

The ideal of life is for an ideal life!

Table of Contents

? Column introduction

Article introduction

1. Common points between v-show and v-if

2. The difference between v-show and v-if

3. Analysis of v-show and v-if principles

v-show principle

v-if principle

4. Usage scenarios of v-show and v-if

?Write at the end


? Column Introduction

Welcome to the front-end entry journey! This column is created for readers who are interested in web development and have just started learning front-end. Whether you are a beginner or a developer with some basic knowledge, we will provide you with a systematic and friendly learning platform here. We update it in the form of questions and answers to present you with selected front-end knowledge points and best practices. By explaining concepts in simple and easy-to-understand terms and providing practical examples and exercises, you can gradually build a solid foundation. Whether it is HTML, CSS, JavaScript or the latest front-end frameworks and tools, we will provide you with rich content and practical skills to help you better understand and apply various technologies in front-end development.

At the same time, we will also pay attention to the latest front-end trends and developments. As Web technology continues to evolve, front-end development is also constantly innovating. We will introduce the latest front-end frameworks, tools and technologies in a timely manner so that you can stay at the forefront and keep pace with the times. By mastering the latest front-end technologies, you will be able to become more competitive in the highly competitive field of web development.

Article introduction

1. Common points between v-show and v-if

We all know that in vue, v-show and v-if have the same effect (excluding v-else). Control whether elements are displayed on the page

The usage is also the same

<Model v-show="isShow" />
<Model v-if="isShow" />
  • When the expression is true, it will occupy the page position
  • When the expressions are all false, they will not occupy the page position.

2. The difference between v-show and v-if

  • Different control methods
  • The compilation process is different
  • Compilation conditions are different

Control method: v-show is hidden by adding css--display:none to the element, and the dom element is still there. v-if Show and hide is to add or delete the entire dom element

Compilation process: v-if switching has a partial compilation/uninstallation process. During the switching process, internal event listeners and subcomponents are properly destroyed and rebuilt; v-show is just simple css-based switching

Compilation conditions: v-if is true conditional rendering, which will ensure that event listeners and subcomponents within the conditional block are destroyed and rebuilt appropriately during the switch process. Only when the rendering condition is false, no operation is performed, and it is not rendered until it is true.

  • When v-show changes from false to true, the component’s life cycle will not be triggered.

  • When v-if changes from false to true, the component’s beforeCreate and create are triggered. code>, beforeMount, mounted hooks trigger beforeDestory of the component when changing from true to false , destoryed method

Performance consumption: v-if has a higher switching cost; v-show has a higher initial rendering cost;

3. Analysis of the principles of v-show and v-if

The specific analysis process will not be discussed here. The general process is as follows

  • Convert the template template into a JS object of ast structure
  • Use the JS object obtained from ast to assemble the render and staticRenderFns functions
  • The render and staticRenderFns functions are called to generate a virtual VNODE node, which contains the information needed to create a DOM node.
  • The vm.patch function uses the VNODE node to create a real DOM node through the virtual DOM algorithm.

v-show principle

No matter what the initial conditions are, the element will always be rendered

Let’s take a look at how it is implemented in vue

The code is easy to understand. If there is transition, execute transition. If not, just set the display attribute directly.

// https://github.com/vuejs/vue-next/blob/3cd30c5245da0733f9eb6f29d220f39c46518162/packages/runtime-dom/src/directives/vShow.ts
export const vShow: ObjectDirective<VShowElement> = {
  beforeMount(el, { value }, { transition }) {
    el._vod = el.style.display === 'none' ? '' : el.style.display
    if (transition & amp; & amp; value) {
      transition.beforeEnter(el)
    } else {
      setDisplay(el, value)
    }
  },
  mounted(el, { value }, { transition }) {
    if (transition & amp; & amp; value) {
      transition.enter(el)
    }
  },
  updated(el, { value, oldValue }, { transition }) {
    // ...
  },
  beforeUnmount(el, { value }) {
    setDisplay(el, value)
  }
}

v-if principle

v-if is much more complicated to implement than v-show because there is also else else-if Other conditions need to be processed. Here we only excerpt a small part of the source code that handles v-if

Returns a node node. The render function determines whether to generate DOM based on the value of the expression.

// https://github.com/vuejs/vue-next/blob/cdc9f336fd/packages/compiler-core/src/transforms/vIf.ts
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
          )
        }
      }
    })
  }
)

4. Usage scenarios of v-show and v-if

Both v-if and v-show can control the display of dom elements on the page.

v-if is more expensive than v-show (directly operates dom nodes to add and delete)

If you need to switch very frequently, it is better to use v-show

If conditions rarely change at runtime, it is better to use v-if

? Write at the end

Please feel free to give me some advice, comment below or send me a private message. Thank you very much.

? I think a certain part of my design is too cumbersome. Is there a simpler or higher-quality packaging method?

? Think some of my code is too old and can provide new API or the latest syntax?

? Don’t understand some of the content in the article

?Answer some questions in my article

? Think that some interactions and functions need to be optimized, and find bugs

? Want to add new features and have better suggestions for the overall design and appearance?

Finally, thank you for your patience in watching. Now that we are here, click Like and go!