How to dynamically assign width to elements in a v-for loop in Vue.JS

I am working with HTML code that looks like this:

                <div v-for="(s, k) in statistics" v-bind:key="s.id" class="single-stat">
                    <div class="stats">
                        {% verbatim %}
                        <div>{{ s.proc1 }}</div>
                        <div class="statid">{{ s.name }}</div>
                        <div>{{ s.proc2 }}</div>
                        {% endverbatim %}
                    </div>
                    <div class="belt1">
                        <div class="belt2" :style="Style(k)"></div>
                    </div>
                </div>

In my Vue object stored in data, I have the following information:

statistics: [
        {name: 'Possession', proc1: 60, proc2: 40, id: 1},
        {name: 'Shoots', proc1: 65, proc2: 4, id: 2},
        {name: 'Passes', proc1: 64, proc2: 40, id: 3},
        {name: 'Fauls', proc1: 44, proc2: 4, id: 4}
    ],

In my methods section, I have defined the following function:

Style: function(k){
        switch(k)
        {
            case 1:
                return { width: statistics[0].proc1 }
            case 2:
                return { width: statistics[1].proc1 }
            case 3:
                return { width: statistics[2].proc1 }
            case 4:
                return { width: statistics[3].proc1 }
        }
    }

However, I am facing an issue with the code. How can I properly set the percentage of width for each belt using the Style method?

Answer №1

You missed adding px after

{ width: statistics[0].proc1 } -> { width: `${statistics[0].proc1}px` }

new Vue({
  el: '#app',
  data: {
    statistics: [
        { name: 'Possession', proc1: 60, proc2: 40, id: 1 },
        { name: 'Shoots', proc1: 65, proc2: 4, id: 2 },
        { name: 'Passes', proc1: 64, proc2: 40, id: 3 },
        { name: 'Fauls', proc1: 44, proc2: 4, id: 4 }
    ],
  },
  methods: {
    style(i) {
      return { width: `${this.statistics[i].proc1}px` }
    }
  }
})
span { display: block; background: #f5f5f5; padding: .5rem; border: 1px solid }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <span
    v-for="(statistic, i) in statistics"
    :key="i" 
    :style="style(i)"
  >
    {{ statistic.name }} width: {{ statistic.proc1 }}px
  </span>
</div>

Answer №2

My recommendation would be to utilize computed properties in this scenario.

new Vue({
  el: '#app',
  data: {
    statistics: [
        { name: 'Possession', proc1: 60, proc2: 40, id: 1 },
        { name: 'Shoots', proc1: 65, proc2: 4, id: 2 },
        { name: 'Passes', proc1: 64, proc2: 40, id: 3 },
        { name: 'Fauls', proc1: 44, proc2: 4, id: 4 }
    ],
  },
  computed: {
    styling() {
      return i => { return { width: `${this.statistics[i].proc1}px` };}
    }
  }
})

Moreover,

 <div v-for="(s, k) in statistics" v-bind:key="s.id" class="single-stat">
                    <div class="stats">
                        {% verbatim %}
                        <div>{{ s.proc1 }}</div>
                        <div class="statid">{{ s.name }}</div>
                        <div>{{ s.proc2 }}</div>
                        {% endverbatim %}
                    </div>
                    <div class="belt1">
                        <div class="belt2" :style="styling(k)"></div>
                    </div>
                </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

What is the best technique for vertically aligning text within two divs placed side by side?

Thank you for taking the time to read this. I have a piece of code similar to the one below. While using line-height works when there is only one line of text, it becomes problematic when the comments section contains multiple lines. I am wondering what w ...

Obtain the URL link from Unsplash where the picture is sourced

As I work on a website, I incorporate a link () to display a random photo. However, the photo refreshes periodically and upon loading the site, all that is visible is this default link: . Is there a method to extract the actual source like so: "". Althou ...

Is there a way to properly assign an index to a multidimensional array in a Vue.js template?

My setup involves utilizing Vue along with a multidimensional array structured like this: myArray = [[1,2,3],[1,2,3],[1,2,3]] To achieve the desired HTML layout shown below (ensuring that data-item counter increments correctly): <div class="row" data ...

Struggling to align text input within a label element

I'm struggling with centering the text on Bootstrap radio buttons that I am customizing. I have tried adjusting the margin, align-content, vertical-align, and text-align properties but the text still won't vertically center. Any suggestions? Her ...

What event is triggered in VueJS when a new click or reset changes the component state?

I am currently working with 2 components on the same page: 1. Item List 2. Lightbox, a classic HTML lightbox without any added Vue.js components I am passing my item ID through a prop to the lightbox, and it is functioning correctly. When I click on an it ...

Creating a Modern Tooltip Menu with HTML, CSS, and Bootstrap

My goal is to design a menu that opens to the right, similar to a tooltip. I have experimented with different bootstrap techniques, but I am encountering difficulties in including HTML li elements within the tooltip. ...

Adapting the visible outcome based on the second figure of a numerical value

Is there a way to automatically change the displayed value using a Vue filter when the last digit of the value falls within a specific range, such as 2-4? I am looking for a solution that can work for all possible intervals like (22-24, 32-34, 622-624... ...

Disabling the scrollbar within angular elements

Trying to remove the two scrollbars from this code, but so far unsuccessful. Attempted using overflow:hidden without success filet.component.html <mat-drawer-container class="example-container" autosize> <button type="button&qu ...

Performing a JavaScript Axios POST request following a series of iterations using a while loop with

Just getting started with async/await and feeling a bit lost. I'm trying to figure out how to send an axios post request after a while loop finishes. Is there a way to wrap the while loop in an async function and await for it? Here's the code s ...

Tips for ensuring that all children within a flex-container have equal heights

I seem to be facing an issue with this problem. My goal is to ensure that all the child divs within a flex container have the same height as the tallest child div, which in this case is 100px. Additionally, I want them to be aligned at the center. I&apos ...

CSS equal-width table columns

My goal is to create evenly spaced columns like in this example. It used to work in a previous version, but now I can't seem to figure out what's causing the difference. Even when copying the old HTML into a jsfiddle and applying the same CSS, it ...

Can the color of an ion-radio be adjusted when it is not selected?

I am experiencing an issue where I need to change the default color (grey) to a specific color of my choice, such as the primary color. I have attempted the following methods: <ion-col sizeXs="12" sizeMd="6" class="radio-box"> <ion-item line ...

Switch the color (make it gray) of the selected tab in the navigation bar

<!-- Customizing the Navbar --> <nav class="navbar navbar-expand-sm bg-primary navbar-dark"> <a class="navbar-brand" href="<?php echo base_url('Controller_dashboard'); ?>"><strong>StuFAP MS</strong></a> ...

Is there a way to incorporate hyperlinks into the Application column of my v-data-table component?

When loading data table from the database, I have included links along with the names of the Applications. However, I only want to display the Application name and open the corresponding link when clicked. headers: [ { text: 'Name&a ...

Exploring SVG Graphics, Images, and Icons with Nativescript-vue

Can images and icons in SVG format be used, and if so, how can they be implemented? I am currently utilizing NativeScript-Vue 6.0 with TypeScript. ...

The issue at hand is that one of the JavaScript buttons is functioning properly, while the other is not playing the video as intended. What steps can

I've been working on a script for my school project website that should make buttons play videos, but I'm running into an issue where it only works for the first button (btn). Programming isn't my strong suit, and I put this together based o ...

Unlocking the potential of Vue within shadow dom environments

I am facing an issue with a shadow DOM that includes the root element and a Vue component. <template> <div class="container"> <div id="app"></div> </div> <script src="http://my-site.com/app/js/vue-compo ...

The hover effect is not altering the color

$(document).ready(function() { $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll > 200) { $(".nav-bg").css({ "background": "#fff", ...

Tips for creating a Nuxt.js server-side rendering (SSR) setup with partially static pre-rendered

While there is plenty of information available on Nuxt SSR and full static sites, I am struggling to find a guide on how to create a hybrid SSR with static pages combined. Currently, I am working on a website using Nuxt SSR and my goal is to statically ge ...

Guide: "Sending an AJAX request upon selecting an item in a Vue.js 'Select' element using vue-resource"

Is it possible to send an ajax request through vue-resource when a specific item is selected from a "Select" in vuejs? Check out the demo here: https://jsfiddle.net/xoyhdaxy/ <div class="container" id="app"> <select v-model="selected"> ...