the absence of any content being shown when using v-else

I'm currently delving into Vue.js and stumbled upon an unusual behavior that I couldn't find any information about on the Internet.

For some reason, the DIV with v-else isn't rendering any content that I place inside it.

I tried to understand why this is happening and all I could find was a suggestion not to use v-for and v-if on the same element (which I don't think I'm doing).

When I remove v-else, everything works perfectly. Below is an example of my code (I believe it's quite self-explanatory, but if not, please let me know and I can provide more details). Thank you in advance for any help!


<template>
  <div v-if="error">{{ error }}</div>
  <div v-if="post" class="post">
    <h3>{{ post.title }}</h3>
    <span v-for="tag in post.tags" :key="tag"> #{{ tag }} </span>
    <p class="pre">{{ post.body }}</p>
  </div>
  <div v-else>
    <Spinner />
  </div>
</template>

<script>
import Spinner from "../components/Spinner.vue";
import getPost from "../composables/getPost";

export default {
  props: ["id"],
  components: { Spinner },
  setup(props) {
        const { post, error, load } = getPost(props.id);
        load();

      return { post, error };
    },
};
</script>

<style>
.post {
  max-width: 1200px;
  margin: 0 auto;
}
.post p {
  color: #444;
  line-height: 1.5em;
  margin-top: 40px;
}
.pre {
  white-space: pre-wrap;
}
</style>

As requested, here is my getPost method:


import { ref } from "vue";

const getPost = (id) => {
  const post = ref({});
  const error = ref(null);

  const load = async () => {
    try {
      // simulate delay
      await new Promise((resolve) => setTimeout(resolve, 1000));

      let data = await fetch("http://localhost:3000/posts/" + id);
      if (!data.ok) throw Error("Sorry, no data available");
      post.value = await data.json();
    } catch (err) {
      error.value = err.message;
    }
  };

  return { post, error, load };
};

export default getPost;

And this is how it appears in json-server:


{
  "posts": [
    {
      "id": 1,
      "title": "Welcome to my blog",
      "body": "Dolor proident consectetur veniam magna Lorem enim laboris cupidatat dolor do commodo officia veniam occaecat. Et incididunt in pariatur commodo fugiat elit eiusmod proident duis proident magna laborum occaecat minim. Ex eu sint cillum proident ea Lorem nulla consequat incididunt tempor reprehenderit laborum sit. Enim nulla sint sunt nulla deserunt officia occaecat sunt velit qui in aliquip. Non nulla et mollit esse ad qui mollit id.",
      "tags": ["webdev", "coding", "news"]
    },
    {
      "id": 2,
      "title": "Top 5 CSS tips",
      "body": "Et incididunt in pariatur commodo fugiat elit eiusmod proident duis proident magna laborum occaecat minim. Ex eu sint cillum proident ea Lorem nulla consequat incididunt tempor reprehenderit laborum sit. Enim nulla sint sunt nulla deserunt officia occaecat sunt velit qui in aliquip. Non nulla et mollit esse ad qui mollit id.",
      "tags": ["webdev", "coding", "css"]
    }
  ]
}

Answer №1

When dealing with an object post, the approach to checking it varies:

<div v-if="post && Object.keys(post).length" class="post">

let post = {}
console.log(post) // results in empty object - true
console.log(Object.keys(post).length) // results in 0 - false

post = null
console.log(post && Object.keys(post).length) // results in null - false

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

Triggering of NVD3 Angular Directive callback occurring prematurely

Lately, I've delved into utilizing NVD3's impressive angular directives for crafting D3 charts. They certainly have a sleek design. However, I'm encountering numerous challenges with callbacks. While callbacks function smoothly when incorpor ...

Browser local storage protection

Utilizing local storage to preserve specific data for my website has been beneficial. Each necessary object is stored so that users can access them on their browser (in chrome: Resource -> Local Storage). My objective now is to make these objects unrea ...

Trimming whitespace from strings within HTML tag attributes can be achieved using various methods

I have been reviewing the .cshtml pages of a website with the aim of adding ID attributes to various divisions and elements for testing purposes. These pages utilize AngularJS, and many of the elements I need to add ID attributes to are part of a list tha ...

Component in Next Js fails to pass props when using getInitialProps

I am facing some challenges with Next Js and could really use some assistance. We have a component where I am utilizing "getInitialProps" to pass props to it during the server-side rendering process. However, no matter what I try, the props do not seem to ...

Adjust the text color of ASP.Net Label based on the presence of a hyphen

I need help changing the text and font color of my ASP.net label based on its content. The label displays a percentage change, and I want negative numbers to be shown in green and positive numbers in red. However, when I try to implement this, I keep enc ...

Extracting dynamic content from a webpage using Selenium with Javascript rendering capabilities

Seeking a way to extract data that populates the SVG elements on a specific page: The page seems to be driven by JavaScript, making traditional BeautifulSoup methods in Python ineffective. After inspecting the network for XHR requests, it doesn't see ...

What is the best way to prevent two paths within an SVG from intersecting with each other?

Currently, I am developing a program that allows the user to draw lines. Once the user completes drawing a line, I receive an array of points in this format: [[x, y], [x, y], ...]. I then convert these points into a path string using the following functio ...

Replicate the functionality of a mouse scrolling event

I have incorporated Jack Moore's Wheelzoom jQuery plugin to zoom and drag an SVG image on my website. However, I also want to include manual zoom in and out buttons for the users. I am considering two options to achieve this - triggering a mouse whe ...

Issue with Three.js GLTF loader peculiar behavior while attempting to incorporate three-dimensional text

I had an idea to import a prebuilt gltf scene created in Blender, then add some 3D text using the ttf loader and manipulate it. Each loader worked perfectly when used separately, but strange things started happening when I combined them into a single scrip ...

Switching focus between windows while working with React

My current setup involves using React. Every time I run yarn start, I can begin coding and see the changes in my browser. However, there's a recurring issue where my terminal keeps notifying me about errors in my code every 10 seconds or so. This cons ...

simulated xhr server along with the locales in polymer appLocalizeBehavior

Currently, I am in the process of developing a web frontend utilizing Polymer. Within my web component, I incorporate various other components such as paper-input or custom web components. To facilitate testing for demonstration purposes, I have integrated ...

Is there a way to prevent advertisements from appearing in npm?

As I execute various npm commands, my console gets bombarded with ads promoting different projects and individuals. While I enjoy contributing to open source projects, I believe the console output of a tool should not be used for advertising. Thank you fo ...

Performing calculations within handsontable

Trying to figure out how to concatenate values from a handsontable grid, I stumbled upon some code on jsfiddle that caught my eye. Here is the link: http://jsfiddle.net/9onuhpn7/4/ The task at hand involves 3 columns A,B,C and an attempt to concatenate ...

Combining AddClass and RemoveClass Functions in Mootools Event Handlers

I am currently in the process of creating a CSS animation, and one aspect involves changing the class name of the body at specific intervals. Since I am relatively new to Mootools (and JavaScript in general), my approach has been to add/remove classes to ...

Detecting when a selectable item is clicked or selected in a Vuetify treeview

I am utilizing a Vuetify treeview with the ability to be selected. <v-treeview :load-children="fetchUsers" :items="user_tree_list" :open.sync="user_tree_open" :active="activeUserUidArray" class ...

Creating a dynamic hyperlink variable that updates based on user input

I am attempting to create a dynamic mailto: link that changes based on user input from a text field and button click. I have successfully achieved this without using the href attribute, but I am encountering issues when trying to set it with the href attr ...

When a React component written in TypeScript attempts to access its state, the object becomes

Throughout my app, I've been consistently using a basic color class: const Color = { [...] cardBackground: '#f8f8f8', sidebarBackground: '#eeeeee', viewportBackground: '#D8D8D8', [...] } export defau ...

Using jQuery to Validate Input Text Control Depending on Radio Selection

How can I ensure that the input text linked to the selected radio option is filled in? For instance, in the example above: If Contact 1's Email radio option is chosen, the Email text field for Contact 1 must not be empty, while the Phone and US Mai ...

The functionality of minified JS code is limited to being copied and pasted directly into the

Trying to explain the issue I'm facing may be a bit tricky, but here it goes: I've been working on an AngularJS app (not live yet) and we felt the need to add tooltips for specific metrics in our tables. After some research, we really liked the ...

Ways to display or conceal text using Vanilla JavaScript

I am struggling to toggle text visibility using Vanilla JS. Currently, I can only hide the text but cannot figure out how to show it again. <button id="button">my button</button> <div> <p id="text">Hello</p& ...