The v-bind:style directive in Vue.js is functioning properly for setting the margin-right property, however

Having an issue with applying a specific style to one of my div elements. When using the following code:

:style="(index + 1) % 2 == (0) && type.Liste.length === indexVin + 1 ? `margin-left : calc((100% - (100% / ${type.Liste.length})) + 6rem);` : null"

The style attribute appears to remain empty, as shown in the screenshot below:

https://i.sstatic.net/NHxVq.png

However, if I change the margin-left to either margin-right or padding-left, it works as expected:

https://i.sstatic.net/QNp8H.png

https://i.sstatic.net/hHr9g.png

After reading up on some documentation, I found that margin-left should be in camelCase. Despite trying this, the issue persists. What's strange is that both margin-right and padding-left, which are in kebab-case, work perfectly fine.

I have made sure there are no conflicting CSS styles applied to the div element besides the one mentioned here. Unfortunately, this did not resolve the problem either.

If you have any insight into why specifically margin-left is causing these issues, please let me know.

Edit: Upon further investigation, I discovered that although console.log functions correctly based on the conditions provided, applying margin-left within the if(even) block does not produce the desired result. However, when placed inside the else if(odd) block, it works properly. A similar behavior was observed for margin-right, yet with opposite outcomes. Any thoughts on why this might be happening?

Check out the additional code snippet below:

methods : {
    computedStyle(index , type , indexVin ) {
      if ((index + 1) % 2 == (0) && type.Liste.length === indexVin + 1) {
        console.log('even and last')
        return `margin-left : calc((100% - (100% / ${type.Liste.length})) + 6rem);`
      } else if (type.Liste.length === indexVin + 1) {
        console.log('odd and last')
        return `margin-right : calc((100% - (100% / ${type.Liste.length})) + 6rem);`
      } else {
        console.log('nothing special')
        return null
      }
    },
}
<div class="padding-block-1" v-for="(type , index) in TypesDeVins" :key="index">
      <div class="tw-flex tw-items-end slider-top"
           :class="[LeftOrRight(index) , FlexDirection(index)]">
        <div class="colonnes-resp-2 tw-flex-shrink-0" :class="LeftOrRightMargin(index , 2)">
          <h4 class="tw-uppercase tw-font-bold text-1-2 letter-spacing-3"
              :class="ColorTitle(index)">Les appellations</h4>
          <h2 class="tw-uppercase tw-text-white tw-font-bold text-2-4 tw-mb-12 letter-spacing-4">{{ type.Nom }}</h2>
        </div>
        <div class="swiper-container" :class="`slider-top-${index}`" :dir="rtl(index)">
          <div class="swiper-wrapper">
            <div class="nom-vin swiper-slide" v-for="(vin , indexVin) in type.Liste"
                 :key="indexVin"
                 :class="slideDir(index)"
                 :style="computedStyle(index , type , indexVin)"
                 >
              <h3 class="tw-text-white tw-font-bold tw-uppercase letter-spacing-3 text-1-2 tw-pb-12">{{ vin.title.rendered }}</h3>
            </div>
          </div>
        </div>
      </div>
    </div>

Answer №1

The guide begins by demonstrating a style binding with an object: https://v2.vuejs.org/v2/guide/class-and-style.html

Here's a sample code snippet from the documentation:

<div class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }"

One suggestion is to extract that style into a computed property for better readability and debugging.

template:

<div :style="computedStyle(index)"></div>

script: (this should be placed under computed, not methods.)

computedStyle() {
  const listLength = this.TypesOfWines[index].List.length;
  return index => {
    return (index + 1) % 2 == (0) && listLength === indexWine + 1
        ? {'margin-left' : `calc((100% - (100% / ${listLength})) + 6rem)`} 
        : null;
  }}

A couple of points to note:

  • The computedStyle function should be in the computed section, not methods.
  • The error message you encountered was correct since "type" was not defined in my example.
  • "Type" refers to a single item from your TypesOfWines array.
  • I introduced a constant to directly define the value you were referencing.

If necessary, utilize a debugger to step through your code and confirm the values are as expected.

Based on your revised code:

computed : {
  computedStyle() {
    return (index, indexWine) => {
      const listLength = this.TypesOfWines[index].List.length;
      const spacing = `calc((100% - (100% / ${listLength})) + 6rem)`;
      if ((index + 1) % 2 == (0) && listLength === indexWine + 1) return {'margin-left' : spacing};
      if (listLength === indexWine + 1) return {'margin-right' : spacing};

      return {};
    }
  }
},

Remember to pay attention to how parameters are utilized within a computed property.

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

What is the process of setting a TypeScript variable to any attribute value?

I have a variable declared in my TypeScript file public variableName: something; I want to use this variable to replace the value of custom attributes in my HTML code <input type="radio" name="someName" id="someId" data-st ...

Issue accessing object property in Handlebars template with ExpressJs

Personalized Routes: router.use(function(req, res, next) { res.locals.currentUser = req.user; next(); }); /* Accessing the home page. */ router.get('/', function(req, res, next) { console.log(res.locals.currentUser.username); ==>> t ...

JavaScript: Dynamically load a script when a particular <a> element is in an active state

<script> function DisplayTag(){ var q1=document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl00_Showcase' ).childNodes[1].innerHTML; var counter1=0; function executeScript(q1,counter1){ q1= document.getElementById( 'ctl00_Co ...

The event listener for onChange on my dropdown menu is not functioning as expected

Hey, I'm trying to achieve something when my select box changes. Here's my code snippet: function Task(){ const prints = (e) =>{ console.log("it prints"); } const prints2 = (e) =>{ console.log("it ...

Using Ajax to dynamically load Wordpress post details and content into a designated div element

I have saved the post-id information in a data-* attribute, and I want to display this content within a div using the &.ajax() function. Below is the code I am currently working on: A list item displaying the post thumbnail <li class="homus-par ...

Iterate through the complex array of nested objects and modify the values according to specified conditions

I am currently iterating through an array of objects and then delving into a deeply nested array of objects to search for a specific ID. Once the ID is found, I need to update the status to a particular value and return the entire updated array. Issue: Th ...

Separate scales for small multiple line charts

Explore the notebook here. I am currently developing a small multiple line chart using d3.v5 on Observable, with the dataset organized as follows: https://i.sstatic.net/QQblnm.png When visualizing, the y scale utilizes the num values from the values arr ...

The tag's onclick function that was dynamically created was not triggering in jQuery

I created a web application using jquery mobile and ran into an issue. I am trying to call a function by clicking on a dynamically generated anchor tag, but it's not working and showing an error that the function is not defined. Any assistance on this ...

The correct way to update component state when handling an onChange event in React using Typescript

How can I update the state for 'selectedValues' in a React component called CheckboxWindow when the onChange() function is triggered by clicking on a checkbox? export const CheckboxWindow: React.FC<Props> = props => { const [selected ...

Retrieve the property type for the specified object

Imagine we have a class with properties like this export class Person { constructor(name: string, age: number) { this.name = name; this.age = age; } public name: string, public age: number } const person = new Person(); Is there ...

Deleting content in a text area when specific text is entered

Is there a way to clear the textarea value if I type in <br>? The code I have right now is shown below. I understand that this may seem like an odd request, but I am experimenting with a typing effect. function eraseText() { document.getElemen ...

Mongodb Node.js - Kerberos module could not be located

After successfully installing mongodb via npm, I encountered an issue when trying to run my app. The error message received was: Error: Cannot find module '../build/Release/kerberos' from '/Users/snorre edwin/Code/raspberry-node- se ...

What approach should be taken to effectively utilize the Vuetify skeleton in a Nuxt project?

I'm relatively new to Vue, Nuxt, and Vuetify and all their components. Currently, I'm developing a Nuxt project with Vuetify and I want to implement the skeleton loader, but I'm facing some challenges. Right now, I'm using the following ...

Is there a way to clear the search box in a wenzhixin bootstrap table without refreshing the page when clicked on?

Is there a way to clear the search box in a wenzhixin bootstrap table without refreshing the page when clicking anywhere on the page? <table id="view_table" data-toggle="table" data-search="true" data-page-list="[5, 10, 20]" data- ...

Difficulty encountered with fetching results using jQuery autocomplete with AJAX as the data source

My autocomplete feature is not working properly with my ajax data source. Here is my code: $("#id_q").autocomplete({ source: function (request, response) { $.ajax({ url: "/search/autocomplete/", dataType: "jsonp", ...

Learn how to efficiently transfer a dynamic subtitle text value from an HTML5 video player to a database

I have successfully developed an HTML5 video player with subtitles. Currently, my goal is to allow the user to submit the subtitle text at a specific timestamp to a database. Despite trying various methods, I am facing challenges in fetching the subtitle t ...

Stop a loop that includes an asynchronous AJAX function

Embarking on my Javascript journey as a beginner, I find myself facing the first of many questions ahead! Here is the task at hand: I have a directory filled with several .txt files named art1.txt, art2.txt, and so on (the total count may vary, which is ...

Is it possible to create a compound editor within a cell in SlickGrid that contains two date fields

Currently, I am implementing SlickGrid with jQuery and I am interested in incorporating a compound editor within a cell similar to example 3a mentioned here. However, instead of two text fields, I would like to have two date fields. Although Example 3 dem ...

Troubleshooting SCSS Issues in NextJS

Can anyone help me with debugging SCSS in NEXT.JS? I've been trying to figure it out but haven't had any luck. When I use @debug on a SCSS module, nothing shows up in the console. Do I need to configure something in the next.config.js file or is ...

Combining Multiple 3D JSON Objects in JavaScript [or jQuery]

Looking to combine multiple JSON objects into one? I have a code snippet that you can use! Here is the code: http://jsfiddle.net/5Uz27/ The issue with this code is that it only merges objects on the first level, causing deeper levels to be overwritten. T ...