Vue: Conditionally display a division depending on v-if, excluding cases where the div returns null

Within my HTML, I have implemented conditional rendering using v-if

    <div v-if="showdiv">
        <p>Content 1 appears here</p>
    </div>
    <div v-if="!showdiv">
        <p>Content 2 appears here</p>
    </div>

My data variable is set up as follows:

data() {
  render {
     showdiv: ''
  }
}

There is an API that determines whether showdiv should be true or false. However, if the API response is slow, I want showdiv to be null so that neither div is displayed. Unfortunately, showdiv is being interpreted as false in such cases and the second div is shown.

    <div v-if="!showdiv">
        <p>Content 2 appears here</p>
    </div>

I want to only display the div when showdiv is true or false. If its value is null, I do not want any div to be rendered. What steps can I take to achieve this desired behavior?

Answer №1

To determine whether the variable showdiv is of type boolean, you can perform an explicit check. Depending on the result of this check, you can then display different divs as shown below:

<div v-if="typeof showdiv === 'boolean' && showdiv">
  <p>Content 1 here</p>
</div>
<div v-if="typeof showdiv === 'boolean' && !showdiv">
  <p>Content 2 here</p>
</div>

Check out the live demo below:

new Vue({
  el: "#myApp",
  data: {
    showdiv: ''
  },
  async mounted() {
    // Pause for 2 seconds
    await new Promise(resolve => setTimeout(resolve, 2000));
    this.showdiv = true;
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<div id="myApp">
  <div>
    <p>The content divs will appear after a few seconds . . .</p>
  </div>
  <div v-if="typeof showdiv === 'boolean' && showdiv">
    <p>Content 1 here</p>
  </div>
  <div v-if="typeof showdiv === 'boolean' && !showdiv">
    <p>Content 2 here</p>
  </div>
</div>

Answer №2

Here is one way you could approach it:

<div v-if="displayBlock">
  <p>This is Content 1</p>
</div>
<div v-else>
  <p>This is Content 2</p>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bootstrap encountered an issue with altering header information

I've been trying to set up a notification system that plays a sound every time someone makes a new post. I'm working with Bootstrap 4 and I've tried inserting JavaScript into the functions page, but no matter how many times I call the ' ...

Utilizing JavaScript text variables as hidden inputs

My JavaScript code is responsible for populating a modal from various sections of a website. Essentially, when the modal expansion button is clicked, it collects all data associated with that particular button press. While this functionality works flawles ...

Creating a feature in Angular JS that allows for each item in a list to be toggled individually

Looking for a more efficient way to toggle individual buttons without updating all at once? Check out this basic example where each button toggles independently by using ng-click="selected = !selected". Instead of updating all buttons at once, you can achi ...

Allow only specified tags in the react-html-parser white list

Recently, I've been working on adding a comments feature to my projects and have come across an interesting challenge with mentioning users. When creating a link to the user's profile and parsing it using React HTML parser, I realized that there ...

What is the equivalent of preg_replace in PHP using jquery/javascript replace?

One useful feature of the preg_replace function in PHP is its ability to limit the number of replacements made. This means that you can specify certain occurrences to be replaced while leaving others untouched. For example, you could replace the first occu ...

Triggering an event through a shared messaging service to update the content of a component

I'm looking for a simple example that will help me understand how I can change the message displayed in my component. I want to trigger a confirmation box with *ngIf and once I confirm the change, I want the original message to be replaced with a new ...

Utilizing JavaScript to call functions from an ASP.NET code file

I am in need of assistance with integrating a JavaScript-based timeline that requires data from an SQL server. I have already developed the queries and JSON conversions using C#.NET functions within a code file associated with an .aspx page. As a newcomer ...

Using TypeORM to Retrieve Data from Many-to-Many Relationships with Special Attributes

Hey there, I'm diving into the world of TypeORM and could really use some guidance. I've been attempting to set up many-to-many relationships with custom properties following the instructions provided here However, I've run into a few iss ...

Is combining Passport.js Google authentication with JWT a logical choice?

I am currently working on integrating Google Login with Passport.js into my MERN stack application. However, I have created this middleware for JWT authentication: const jwt = require("jsonwebtoken"); const config = require("config"); module.exports = a ...

Issues with JQuery Ajax rendering in browser (suspected)

I'm encountering an issue on my webpage. I have a div with two hidden fields containing values of 0 and 2, respectively. Upon clicking a button that triggers an AJAX query, the div contents are updated with hidden field values of 1 and 2. However, it ...

List of nested objects converted into a flat array of objects

Looking to transform a data structure from an array of objects containing objects to an objects in array setup using JavaScript/Typescript. Input: [ { "a": "Content A", "b": { "1": "Content ...

Swapping out components or features within AngularJS

Is it possible to make my dependencies interchangeable in AngularJS? For example, if I have a service named myService stored within the module myDependency, how can I switch out myDependency with a new service without disrupting the main application? Shou ...

Identifying the conclusion of a folder being dropped in vanilla JavaScript

I am working on determining when a directory tree has been completely traversed after being dropped onto a page. My goal is to identify the point at which the next process can begin once the entire folder and its sub-directories have been processed by the ...

Guide on integrating vue.js into expressjs using pug

Below is the code I have attempted: In my .pug file: extends layout block content h1= title p Welcome to #{title} script(src='/javascripts/custom_vue.js') div(id="app") {{ message }} Here is custom_vue.js: new Vue({ el: &apos ...

Universal Module Identifier

I'm trying to figure out how to add a namespace declaration to my JavaScript bundle. My typescript class is located in myclass.ts export class MyClass{ ... } I am using this class in other files as well export {MyClass} from "myclass" ... let a: M ...

Exploring the DOM with jQuery to effectively select multiple elements

I am currently attempting to locate and select all elements with the "findme" class, and then identify the selects that are located nearby. http://jsfiddle.net/R93md/1/ Specifically, I have experimented with $(".findme").parent().prev().first(); Once ...

What is the best way to retrieve the value of a text box in VUEjs using its unique identifier?

In my form, there are a total of two text boxes with predefined values. However, I am looking for a way to retrieve the value of one specific textbox based on the entered ID number. For example, if I input "1," I expect to see the value of text box 1 only ...

Tips for temporarily preventing a digest cycle when modifying a scope variable

Is there a way to edit an array of objects in AngularJS, linked to the view through ng-repeat, without updating the scope until all objects have been modified? Consider this scenario: I need to update each object in the array and only then reflect the ch ...

Ugly consequences arise as Gulp stumbles upon uncharted territory during the uglify

I'm experiencing an issue with my squish-jquery task. Every time I run it, I encounter the following error: Starting 'squish-jquery'... events.js:85 throw er; // Unhandled 'error' event ^ Error at new JS_Par ...

Modify the input field in the datepicker to resemble a button

How can I transform an input field into a button that looks like this https://i.sstatic.net/BDk5C.png rather than this https://i.sstatic.net/UdXoE.png? The simple switch of tag names doesn't seem to work. Any suggestions on how to achieve this? cla ...