惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cloudbric
Cloudbric
T
Threat Research - Cisco Blogs
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog
P
Privacy & Cybersecurity Law Blog
H
Help Net Security
云风的 BLOG
云风的 BLOG
G
GRAHAM CLULEY
Spread Privacy
Spread Privacy
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
Arctic Wolf
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
P
Privacy International News Feed
Blog — PlanetScale
Blog — PlanetScale
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence
The Register - Security
The Register - Security
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
PCI Perspectives
PCI Perspectives
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
A
About on SuperTechFans
W
WeLiveSecurity
GbyAI
GbyAI
V
Vulnerabilities – Threatpost
The GitHub Blog
The GitHub Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Check Point Blog
Y
Y Combinator Blog
月光博客
月光博客
Scott Helme
Scott Helme
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
U
Unit 42
G
Google Developers Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Threatpost
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Google Online Security Blog
Google Online Security Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cisco Talos Blog
Cisco Talos Blog
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 司徒正美

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
How to Show/Hide Elements in Vue
Dmitri Pavlutin · 2021-11-03 · via Dmitri Pavlutin Blog

Hiding and showing elements on a web page is an often occurring UI-related task. You might want to toggle the visibility of some detail sections, tooltips, and more.

In this post, you'll learn how to hide elements on a web page using 3 approaches provided by Vue:

  • When the element is completely removed from DOM using v-if;
  • When the element is hidden using display: none applied by v-show;
  • Applying the visibility: hidden using the :class binding.

Table of Contents

  • 1. Hiding using v-if
    • 1.1 When to use v-if
  • 2. Hiding using v-show
    • 2.1 When to use v-show
  • 3. Hiding but keeping the space
  • 4. Conclusion

1. Hiding using v-if

v-if is a built-in Vue directive that accepts boolean values:


<div v-if="value">I am an element</div>


v-if deals withing showing/hiding the element as follows:

A) If the value supplied to v-if is true (or generally a truthy value), then the element is inserted into the DOM;

B) Otherwise, if the value supplied to v-if is false (or generally a falsy value), then the element is not inserted into the DOM.

Let's consider the following example:


<template>

<div v-if="value1">I'm rendered!</div>

<div v-if="value2">I'm not rendered!</div>

</template>

<script>

export default {

data() {

return {

value1: true,

value2: false

}

}

};

</script>


Open the demo.

When the above component runs, here's what HTML content is inserted into the web page:

The first element is rendered because v-if="value1" was supplied with a true value. The second element, however, isn't rendered into the DOM because v-if="value2" was supplied with a false.

In simple words, v-if directive allows you to show or hide the element just by inserting or not the element into the DOM. Brutally simple.

1.1 When to use v-if

When v-if directive is assigned with false, Vue also doesn't initialize the event listeners on the element, even if you explicitly use the event directives.

v-if toggling is relatively expensive (since each time you change v-if value the element is inserted/removed from DOM, as well event listeners are initialized/uninitialized) compared to v-show (presented in the next section). But it has a low initialization cost if the element is initially hidden.

You'd use v-if on the elements which visibility isn't toggled too often and is initially hidden. For example, to show/hide a section having detailed information about an entity.

Challenge: would v-if render the element if assigned with 0? What about '0'?

2. Hiding using v-show

Often it's useful to keep the element present in the DOM, but have it visually hidden using CSS styles.

v-show is a built-in directive that shows or hides the element visually:


<div v-show="value">I am an element</div>


v-show deals with showing the element as follows:

A) If the value supplied to v-show is true (or truthy), then the element is visible;

B) Otherwise, if the value supplied to v-show is false (or falsy), then the element is hidden, but still rendered in the DOM.

Let's look at the following example:


<template>

<div v-show="value1">I'm visible!</div>

<div v-show="value2">I'm hidden!</div>

</template>

<script>

export default {

data() {

return {

value1: true,

value2: false

}

}

};

</script>


Open the demo.

When you run the above component both elements are rendered into the DOM:


<div>I'm visible!</div>

<div style="display: none;">I'm hidden!</div>


The first element is visible on the screen. However, the second is hidden because Vue applies display: none inline style, thanks to v-show="false".

display: none applied to an element makes the element disappear completely.

Challenge: how can you implement in Vue a button that toggles the display of an element? Share your solution in a comment!

2.1 When to use v-show

v-show, when assigned with false, applies display: none inline style and hides the element visually and makes almost no modifications to the DOM.

Thus toggling the element's visibility using v-show is relatively cheap (compared to v-if described above), so you might use this directive with an element which visibility is toggled often.

3. Hiding but keeping the space

What if you need to hide the element's content while keeping the space it occupies? The CSS style that hides the element content but keeps its space is visibility: hidden.

Unfortunately, you cannot use v-show directive because it applies only display: none style.

But a viable solution is to use :class binding, which is pretty flexible in Vue. When the object literal { className: boolValue } is assigned to the :class, Vue applies the "className" as a class to the element if boolValue is true.

Let's create a CSS class invisible having the visibility: hidden style. Then, using the :class binding and an object literal you can apply the invisible class to an element:


<template>

<div :class="{ invisible: !value1 }">I'm visible!</div>

<div :class="{ invisible: !value2 }">Only my space is visible!</div>

<div>Dummy text</div>

</template>

<script>

export default {

data() {

return {

value1: true,

value2: false

}

}

};

</script>

<style>

.invisible {

visibility: hidden;

}

</style>


Open the demo.

Open the demo you'd see the elements I'm visible and Dummy text, and a space in between the two — the hidden second element.

The above example renders the HTML content:


<div class="">I'm visible!</div>

<div class="invisible">Only my space is visible!</div>

<div>Dummy text</div></div>


<div :class="{ invisible: !value2 }">Only my space is visible!</div> applies the invisible class to the element because value2 is false (I know the negation here is confusing!).

Note that you can also hide the element by using opacity: 0, or even offset the element out of the viewport using position: absolute; left: -9999px. Just create the appropriate CSS class and then toggle it using :class.

4. Conclusion

Vue gives you a bunch of good ways to hide the element on the screen.

When using v-if="false" the element isn't rendered at all in the DOM.

When using v-show="false" the element is rendered in the DOM, however, Vue applies the inline style display: none that hides the element completely.

Also, do not forget about the powerful :class binding if you'd like more visibility customization.

To hide the element but keep its space use :class="{ invisible: !value }" to assign invisible class (which has visibility: hidden style applied to it).