When I incorporate multiple conditions in the ternary operator, my Vue App fails to load

When working on a weather display app and using Vue for learning purposes, I originally had the following expression that worked fine:

<div id="app" :class="typeof weather.main != 'undefined' && weather.main.temp < 16 ? '' : 'warm' ">

However, when I tried to change the expression to:

<div id="app" :class="typeof weather.main != 'undefined' && weather.main.temp < 16 ? '' : weather.main.temp < 18 ? 'chill' : weather.main.temp < 30 ? 'warm' : 'hot' ">

The app would compile without any errors, but nothing would load and the console remained blank.

Answer №1

The issue at hand pertains to operator precedence. The expression is being assessed as:

(typeof weather.main != 'undefined' && weather.main.temp < 16) ? '' : (weather.main.temp < 18 ?'chill': weather.main.temp < 30 ?'warm':'hot')

This leads to the scenario where weather.main.temp < 18 is evaluated even when weather.main happens to be undefined.

The remedy lies in refraining from incorporating convoluted code into the template and instead transferring it to a computed property where it can be composed in a clear and manageable format. The utilization of a typeof check for undefined values is necessary solely for variables that may potentially be undefined. Optional chaining capabilities can be harnessed in computed properties within Vue 2 to bypass condition checks, just as in templates within Vue 3.

An alternative approach could adopt the following structure:

computed: {
  appClass() {
    if (!weather.main || weather.main.temp < 16)
      return '';
    else if (weather.main.temp < 18)
      return 'chill';
    else if (weather.main.temp < 30)
      return 'warm';
    else 
      return 'hot';
  }
}

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

How to create a continuous fade effect on text using jQuery/Javascript

I'm in the process of creating a website and I want to create a fading effect for multiple words at specific time intervals with an infinite loop. Here's a visual example of what I'm aiming for: https://i.sstatic.net/mW4yS.gif I've ma ...

Utilize Vue CLI 3 to enable popups in arcgis API JS

I've been attempting to enable popups from the ArcGIS API JS to show using the Vue-CLI 3 framework. Unfortunately, even with a simple sample code, I'm unable to make it function properly. Below is the code initially written in vanilla JS: <!DO ...

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 ' ...

Is it possible to have individual JavaScript files for each action in Rails 3?

I developed an app to manage various "Games". Within the "show" view, I want to display game details along with a select option for quick navigation to a specific game. Implementing the quick-jump functionality would involve utilizing JavaScript. However, ...

What is the process of extracting information from individual getters in Vue?

Can you explain how to fetch data using a specific getter in Vue? this.$store.getters('client/list')) An error occurred: TypeError - _this.$store.getters is not a function at eval (Login2.vue?3936:64) ...

Automating the testing of Google Analytics for every event triggered with Selenium WebDriver

Currently, I am in the process of automating Google Analytics testing using Selenium WebDriver Java bindings on our website. The site is equipped with Google Analytics tracking events attached to key elements, and my goal is to confirm that clicking a spec ...

Is there a way to retrieve the left offset of a floating element even when it is positioned outside the viewport?

My current situation involves creating several panels that are stacked side by side within a main container. Each panel takes up 100% of the viewport width and height. I want to be able to horizontally scroll to each panel when clicking on their respective ...

Include the image source and hyperlink in List.js

I have successfully implemented a plugin called List.js in my project. However, I am facing difficulty in adding image src or href values within it. The plugin seems to work well with other tags. If you want to check out List.js, here is the URL: For doc ...

Sinon causing 'unsafe-eval' error in Chrome extension unit tests

Recently, I've been conducting unit tests on my Chrome extension using Mocha, Chai, and Sinon. However, I encountered an issue when attempting to stub an object from a method: EvalError: Refused to evaluate a string as JavaScript because 'unsafe ...

'Without the need to refresh the page, assign a JavaScript variable from JSP on the server side.'

I'm looking for a way to assign a JavaScript variable from JSP without triggering a full page reload. While my current code successfully sets the variable, it also causes the entire page to refresh as a side effect. Here's an example in the exam ...

Physijs: Administer a sudden force to a certain point within the 3D object

I need to add some force and impulse to a 3D model, with the physics engine Physijs adjusting the rotational and translational velocity based on the object's mass distribution. Is there a way to accomplish this effectively? It seems like Physijs only ...

Utilizing Angular's expressions in conjunction with HTML5 data attributes

I am a beginner in AngularJS and currently learning. I am working on developing an app that makes an API service call to retrieve a value and then updates it on a dashboard. Here is the HTML code snippet: <div class="span3" ng-controller="rookieContro ...

Out-of-sync movement in animated characters

Looking for some assistance with my page coding. I have a scenario where two stars are moving around a button, simulating an animation by incrementing the CSS properties top and left. Initially, everything appears fine and they move synchronously. However, ...

Ways to bring GIFs into NextJS

I am currently working on my portfolio website using Nextjs and I would like to incorporate gifs into the site. However, I have been struggling to figure out how to do so. Below is the code that I have been working with: https://i.stack.imgur.com/zjoiD.pn ...

Struggling with collaborating with an assistant in handlebars and express operations

When attempting to utilize helpers, an error arises: ReferenceError: a is not defined The goal is to display home.hbs located under the views directory. The file contains: <li class="{{#if_eq title "Home"}}active{{/if_eq}}"> <a href="/">H ...

Is there a way to pause and await the completion of an axios post request within a different axios interceptor?

Here are my axios interceptors: instance.interceptors.request.use( (config) => { const accessToken = localStorage.getItem("access_token"); const auth = jwt_decode(accessToken); const expireTime = auth.exp * 1000; co ...

The POST method functions properly in the local environment, however, it encounters a 405 (Method Not Allowed) error in the

After testing my code locally and encountering no issues, I uploaded it to Vercel only to run into the error 405 (Method Not Allowed) during the POST method. Despite checking everything thoroughly, I'm unable to find a solution on my own. Your assista ...

How can I access properties of generic types in TypeScript?

Converting the generic type to any is a valid approach (The type E could be a typescript type, class, or interface) of various entities like Product, Post, Todo, Customer, etc.: function test<E>(o:E):string { return (o as any)['property' ...

Converting a JavaScript timestamp into a human-readable date and time using as.POSIXct in R

Is there a way to convert a timestamp from this format into a readable human date? I have generated the timestamp using JavaScript: Date.now(); An example of the output is: 1468833354929 After storing it in a database, when I attempt to convert it usi ...

Form submission failure due to dynamic input manipulation

I am encountering an issue with a dynamic form that allows users to add and remove inputs. Although the form functions correctly visually, the values from inputs created by the JavaScript function are not being retrieved when the form is submitted. If more ...