Having trouble with Vuejs Ternary Operator or Conditional in v-bind-style?

Having some unexpected issues while trying to implement a style conditional for items in Vuejs.

I have come across Stack Overflow posts on how to use a ternary, either through an interpolated string or a computed style object. I've attempted both methods but neither seem to be working correctly.

Here's the code snippet:

<div 
    :class="{'radar__container':true,'inactive':inactive}"
    :style="[inactive ? {getStyleRadarContainerInactive} : {getStyleRadarContainer}]"
  >

To apply this style:

computed: {
    getStyleRadarContainer: function(){

        let styleRadarContainer = {
            left: this.radarItem.posX*100 + '%', 
            top: this.radarItem.posY*100 + '%',
            transform: 'translate(-50%,-50%) scale(' + this.radarItem.scale + ')',
            opacity: this.radarItem.opacity,
        }

        return styleRadarContainer;
    },
    getStyleRadarContainerInactive: function(){

        let styleRadarContainerInactive= {
            left: this.radarItem.posX*100 + '%', 
            top: this.radarItem.posY*100 + '%',
            transform: 'translate(-50%,-50%) scale(0)',
            opacity: this.radarItem.opacity,
        }

        return styleRadarContainerInactive;
    },
  }

Even though the intention is for each item to scale down (due to the scale(0) in the opacity property), the style attribute fails to render at all. I also experimented with an inline ternary on the style prop (as the scale is the only changing factor between the two properties):

transform: 'translate(-50%,-50%) ' + inactive ? 'scale(' + radarItem.scale + ')' : 'scale(0)',

What could be causing this issue?

Answer №2

When using the style binding, make sure to pass in an object directly instead of wrapping the ternary in unnecessary square brackets that create an array containing an object. Also, avoid nesting the returned object by removing the unnecessary brackets around the ternary:

<div 
    :class="{'radar__container':true,'inactive':inactive}"
    :style= "inactive ? getStyleRadarContainerInactive : getStyleRadarContainer"
  >

Remember that when adding a variable containing an object to another object without specifying a property name, the variable name itself will be used as the property name.

var myObject = {
  property: 'value'
};

$('#output').html(JSON.stringify({myObject}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output"></div>

Answer №3

It is possible to implement this functionality by utilizing the spread operator in the following manner:

:style= "[inactive ? {...getStyleRadarContainerInactive} : {...getStyleRadarContainer}]"

Answer №4

The solution provided was unsuccessful because it included double curly brackets.

  :style="[{ obj: { styleObject }}]" // This approach will not work

You have two options: you can either use an array containing styleObjects or just a single styleObject.

For example:

  :style="[ { color: 'blue' } ]"
  :style="{ color: 'blue' }"

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

JS Equal Heights is a JavaScript plugin designed to ensure

Good evening, A while back, I implemented a JavaScript code snippet to create equal height columns on my website. The initial script looked like this: <script type="text/javascript"> var maxHeight = 0; $(".level").each(function(){ maxHe ...

Ways to avoid automatic error correction when running npm lint?

Utilizing the Vue CLI, I developed a Vue3 app with a Prettier/Eslint configuration. Upon making changes to the main.ts file as shown below: import { createApp } from "vue"; import App from "./App.vue"; import router from "./router& ...

When positioning 2 divs on top of each other, rotating one by 180 degrees causes it to be considered secondary in the visibility hierarchy. What is the reason behind this?

While delving into the realm of HTML, I stumbled upon a concept that has left me perplexed. Upon stacking two divs on top of each other, I observed an interesting phenomenon where rotating the second div by 180deg (i.e transform:rotateY(180deg)), causes t ...

Guide on creating a global router function in nuxt.js

I am currently working with Vue.js and Nuxt.js, but I have encountered an issue with the router's functions. In a pure Vue setup, I would typically include code in main.js like this: const router = new Router({ routes:{ [...] } }) route ...

Is it possible to utilize npm request multiple times within a single route and showcase the outcomes on a single page?

Is it possible to utilize the node module "request" multiple times within a single route, and have the outcomes presented on a solitary rendered ejs template page? Objective: The aim is to exhibit eBook details from the iTunes Store by utilizing their Sea ...

Is there a way to set a custom width or make the description responsive?

Is there a way to ensure that the description is responsive and automatically goes to the next line instead of extending horizontally? Although using textField could fix this issue, I also need to adjust the padding and outline. Are there any alternative s ...

Tips for modifying the icon of a div with a click event using vanilla JavaScript

My goal is to create a functionality where clicking on a title will reveal content and change the icon next to the title. The concept is to have a plus sign initially, and upon clicking, the content becomes visible and the icon changes to a minus sign. C ...

Pause until the existence of document.body is confirmed

Recently, I developed a Chrome extension that runs before the page fully loads by setting the attribute "run_at": "document_start". One issue I encountered is that I need to insert a div tag into the body of the webpage as soon as it is created. However, a ...

Angular 14 debug error: Incorrect base path setting

Whenever I go for a run, I have to specify a starting point such as /pis/ ng serve --serve-path /pis/ Even after following these instructions, nothing seems to load. Can anyone lend a hand with setting a starting point in the ng serve process? ...

Acquire the model from a field within an Angular Formly wrapper

I'm in the process of designing a wrapper that will exhibit the model value as regular text on the page. Once the mouse hovers over this text, it transforms into a Formly field, which works perfectly fine. However, I'm encountering an issue where ...

Can CSS achieve Turing completeness?

As far as my understanding goes, CSS is not considered Turing complete. However, I admit that my knowledge of CSS is quite limited. Can CSS be classified as Turing complete? ...

Unable to use onSubmit with enter key in render props (React)

I am looking to include a button within a form that can trigger the onSubmit event when the user presses the Enter key. Here is an example of a functional solution: <form onSubmit={() => console.log('ok')}> <button type="submi ...

Suggestions on how to refactor redundant code in various peer AngularJS controllers for handling $intervals

In my compact single-page application, I have implemented multiple tabs to display operational status information for different applications. Each tab is associated with a controller that creates $interval objects to make AJAX calls to fetch status data fr ...

Struggling to compile SASS in VueJS with WebpackSimple?

I recently set up a fresh installation of VueJs using webpack simple and encountered an issue with configuring SASS to CSS conversion. The documentation states that it supports SCSS, but I need assistance in setting up SASS specifically with the lang="sass ...

Utilizing localstorage data in angular 2: A comprehensive guide

Is there a way to utilize data stored in localstorage for another component? This is what the localstorage service looks like: localStorage.setItem('currentUser', JSON.stringify({ username: username, token: success, res: res.data })); I am inte ...

What is the process for extracting JSON values by specifying keys within a nested JSON structure?

I am attempting to extract specific JSON values for particular keys from a JSON structure. I have made the following attempt: var jsonstring; jsonstring = JSON.stringify(myjsonObjectArray); alert(jsonstring);//displaying the JSON structure below jsonstri ...

What could be causing my <UL> to not properly expand around the <LI> items inside of it?

I am currently working with WordPress and have created a menu using a list structure. Here is an example of how it looks: <ul> <li>Home</li> <li>About</li> <li>ParentItem <ul> <--- The heig ...

What is the method to spin an item in three js while keeping its axis in focus?

Looking to rotate a globe object around its y-axis smoothly? I have come across a helpful function for achieving this: function rotateAroundObjectAxis(object, axis, radians) { var rotationMatrix = new THREE.Matrix4(); rotationMatrix.makeRotationAxis ...

Problem with z-index in VueJS: Child div z-index not functioning within v-dialog

I am facing an issue where I have brought a span to display a loading image inside the v-Dialog of a vuejs screen. The problem is that the v-dialog has a z-index of 220 set as inline style, causing my new span (loading image) to appear below the v-dialog. ...

Guide on Executing a Callback Function Once an Asynchronous For Loop Completes

Is there a way to trigger a callback function in the scan function after the for await loop completes? let personObj = {}; let personArray = []; async function scan() { for await (const person of mapper.scan({valueConstructor: Person})) { ...