Leveraging Template Variables for Styling in Vue 3's CSS Classes

Struggling to find the perfect way to utilize variables returned by Vue functions in CSS inline styles, specifically with the "width" style.

I have two variables that are returned to the template and can be used with the {{}} syntax, but not directly as a CSS style.

This example works smoothly:

Total Staked {{ gems }}/{{ size }} ({{
              Math.round((gems / size) * 100)
            }}%)

Resulting in: Total Staked 200/350 (57%)

My goal is to incorporate that dynamic percentage (57%) into a css inline style like so:

<div class="bg-black h-2 rounded-md text-white" style="width: 57%"></div>

where the width: 57% adjusts dynamically.

Using Vue 3 along with Tailwind CSS

Check out the Codepen for reference: https://codepen.io/johnwinsor/pen/RwxvdZZ

Appreciate your help! Thank you!

Answer №1

To apply styles dynamically in Vue.js, you can utilize computed properties:

new Vue({
  el: "#app",
  data() {
    return {
      coins: 500,
      dimension: 300
    };
  },
  computed: {
    barWidth() {
      return Math.round((this.coins / this.dimension) * 100)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" integrity="sha512-wnea99uKIC3TJF7v4eKk4Y+lMz2Mklv18+r4na2Gn1abDRPPOeef95xTzdwGD9e6zXJBteMIhZ1+68QC5byJZw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<div id="app">
  <div>
<!--     Progress Bar -->
    <div class="w-2/3 h-2 pl-5 pr-5 m-auto">
        <div class="w-full h-2 mt-6 mb-2 bg-blue-500 rounded-md">
           <div class="bg-black h-2 rounded-md text-white" :style="`width: ${barWidth}%`"></div>
        </div>
    </div>
<!--     Statistics -->
    <div class="flex flex-wrap justify-center align-center pb-5">
      <p class="text-blue-600">
        Active Coins {{ coins }}/{{ dimension }} ({{ barWidth }}%)
      </p>
    </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

Show an item from a list in Vue.js depending on the current time

When retrieving a list of objects (trips) from an API, I need to determine if any trip object meets the following criteria: A trip object includes -> startTime, estimatedTime, begin, destination Criteria: If there is a trip where startTime + estimated ...

Having trouble with getting the second JavaScript function to function properly?

I am facing an issue with the second JavaScript function. When I click the 'Send Mail' button, it should call the second function and pass it two values. However, the href line (second last line in the first function) is not rendering correctly. ...

What is the process of converting a value from an HTML form into a PHP variable?

I am looking to update the order preparation time. I have created an HTML form, but I am facing issues passing it into a PHP variable after this code block. I have tried using Cookies and POST method, but neither has helped me so far. <form> ...

Wait for Axios Request Interceptor to complete before sending another ajax call

One feature I have added is a request interceptor for all axios calls. This interceptor checks the JWT token and automatically refreshes it if necessary. axios.interceptors.request.use((config) =>{ const currentState = store.getState(); // get upd ...

Guide on debugging Express.js server code on Node with Visual Studio Code by Attaching to a live process

Here is a list of the tools I have: Latest Visual Studio Code Express js Node js Take a look at my Attach configuration below: { "version": "0.1.0", // List of configurations. Add new configurations or edit existing ones. "configurations": ...

problem arising from the origin preventing me from utilizing localStorage in conjunction with JSDOM

Currently, I am facing an issue while trying to load a webpage in a node environment using JSDOM. The webpage relies on localStorage for its functionality. I have attempted to load the webpage by utilizing JSDOM's URL configuration option and accessi ...

Is it possible to selectively hide the remove icon for certain files within the antd Upload component?

Is there a way to specifically hide the remove button in the Antd Upload component for files that meet certain criteria? I am aware of the "showRemoveIcon" prop which disables the remove icon for every file, but is there a way to do this for only one fil ...

Display or conceal section based on selected checkboxes

I'm currently working on a JavaScript script that involves showing/hiding elements based on radio button and checkbox selections. The goal is to reveal a hidden section when certain checkboxes are checked, as illustrated in the screenshot below: http ...

What is the best way to ensure that two divs have aligned bottom edges?

I have a set of div containers positioned in different columns within a grid layout. I am looking for a way to identify the containers where the bottom edge is less than 50px higher than any other container, and adjust their heights so they align perfectly ...

Mastering sorting in AngularJS: ascending or descending, the choice is yours!

I have set up a table view with infinite scroll functionality. The table contains 2000 objects, but only shows 25 at a time. As the user scrolls to the bottom, it loads an additional 25 elements and so on. There is a "V" or "^" button in the header that sh ...

Tips for optimizing Jquery selectors to streamline recurring functions

I have 9 "service node" divs in my HTML code, each containing a hidden div and a button that triggers the rotation of the button by 45 degrees and reveals the hidden div. The challenge I am facing is that I have been using repetitive functions for each ser ...

Create a sleek 2-column design featuring a bonus scroll bar exclusively using CSS styling

In my current project, I have a unique challenge. I am working with a list of flattened div elements and unfortunately, I am unable to edit the HTML markup to add any structures. The first div in the list is quite long, and I would like to place it in a se ...

Navigating to User's Specific Info Page using Node.js

Would love some input on my current issue. I have a table featuring a list of users, and my goal is to display user information in detail whenever a user (which corresponds to a row in the table) is clicked. The process involves identifying which user was ...

The proper method for developing Vue components that are dependent on the parent build tools

In my experience, this issue might also arise in other frameworks with plugin/component ecosystems that rely on specific build tools (such as React components with JSX). While Vue serves as my use-case. Having developed numerous Vue components as single . ...

Here's a helpful guide on verifying the presence of a value within an array in Quasar

const myproducts = ref([]) const items = ref([ { id: 1, item: 'Vaporub 50Gm' , barcode: '123456'}, { id: 2, item: 'Herbal Cool Oil (300+100)Ml', barcode: '123456' }, { id: 3, item: 'live Oil Bp 70M ...

Using a for loop in Flot to display data from a JSON file

I am working on creating a dynamic flot graph that will adjust based on the data provided. The information for my flot graph is in JSON format, and here's an example of the dataset: { "total":[[1377691200,115130],[1377694800,137759],[1377698400,1 ...

Tips for simulating an axios request that returns an image buffer

I am attempting to simulate an axios api call that returns an image buffer as shown below: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e1 00 de 45 78 69 66 00 00 49 49 2a 00 08 00 00 00 06 00 12 01 03 00 01 00 00 00 01 00 ... ...

VUE and Axios: Issue with Request Header Content-Encoding Disallowed by Access-Control-Allow-Headers in Preflight Response

Currently, I am working on creating a quick web application for fun that utilizes the League of Legends API. While some API calls are successful, I am encountering an issue with one specific message stating: "Request header field content-encoding is not a ...

Encountering an issue when passing a response using coverage.js

I am utilizing coverage.js to showcase data. When I pass my variable containing the coverage response into an HTML file, similar to how it's done in Angular to display expressions, I encounter a syntax error: <div class="container" style="margin- ...

Issue with background opacity not functioning properly in Internet Explorer 8

I am facing an issue with displaying 2 images in IE8 and IE9. Below is the code snippet causing the problem: .ui-widget-content { border: 0px solid #aaaaaa/*{borderColorContent}*/; background: rgba(0, 0, 0, 0.1) ; /*{bgColorContent}*/ url(images ...