How about passing some vue props data over?

I am trying to assign different colors based on the percentage of each of the 5 batteries. However, the issue I'm facing is that the color spread is not specific to each individual battery.

I suspect this issue arises because the bmss data is being received all at once. Unfortunately, I am unsure of how to resolve this. Currently, I have managed to change the battery color according to the percentage and display it in green. View image of all batteries

The main problem lies with the colormap. Color-coded battery image

Link to code sandbox for reference

Vue Data

  <template>
      <div id="charging_div" class="frame">
        <div>
          <div id="charging_top_div">
            <div v-for="(bms, index) in bmss" :key="index">
              <div id="charging_left_div">
                <ProgressBattery :bmss="bms" />
                <span>{{ bmss[index].soc }}</span>
              </div>
            </div>
          </div>
          <div class="accumulate">
            <p>{{ time }} kW</p>
            <p>{{ power }} kW</p>
          </div>
          <div id="charging_bottom_div">
            <button id="harging_btn" v-on:click="click_stopCharging_btn">
              Stop Charging
            </button>
          </div>
        </div>
      </div>
    </template>
    
    <script>
    import ProgressBattery from "./ProgressBattery.vue";
    
    export default {
      name: "connect",
    
      components: {
        ProgressBattery,
      },
    
      data() {
        return {
          time: "",
          power: "",
          bmss: [
            {
              soc: 5,
            },
            {
              soc: 45,
            },
            {
              soc: 20,
            },
            {
              soc: 100,
            },
            {
              soc: 30,
            },
          ],
        };
      },

Vue Fetching

 <template>
      <div id="progress-bar-battery">
        <div class="box">
          <span v-if="this.bmss.soc >= 100" class="item" id="v100"></span>
          <span v-if="this.bmss.soc >= 90" class="item" id="v90"></span>
          <span v-if="this.bmss.soc >= 80" class="item" id="v80"></span>
          <span v-if="this.bmss.soc >= 70" class="item" id="v70"></span>
          <span v-if="this.bmss.soc >= 60" class="item" id="v60"></span>
          <span v-if="this.bmss.soc >= 50" class="item" id="v50"></span>
          <span v-if="this.bmss.soc >= 40" class="item" id="v40"></span>
          <span v-if="this.bmss.soc >= 30" class="item" id="v30"></span>
          <span v-if="this.bmss.soc >= 20" class="item" id="v20"></span>
          <span v-if="this.bmss.soc >= 10" class="item" id="v10"></span>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      name: "ProgressBattery",
      props: {
        bmss: {
          type: Object,
          required: true,
          default: function () {
            return [{ soc: 0 }];
          },
        },
      },
      mounted() {
        if (this.bmss.soc >= 61) {
          for (let i = 1; i < 11; i++) {
            document.getElementById(`v${i}0`).style.backgroundColor = "#4ee533";
            console.log(this.bmss.soc + "Green" + `v${i}0`);
          }
        } else if (this.bmss.soc >= 21 && this.bmss.soc <= 60) {
          for (let i = 1; i < 7; i++) {
            document.getElementById(`v${i}0`).style.background = "#FFA500";
            console.log(this.bmss.soc + "Orange" + `v${i}0`);
          }
        } else if (this.bmss.soc <= 20 && this.bmss.soc >= 0) {
          for (let i = 1; i < 3; i++) {
            document.getElementById(`v${i}0`).style.background = "#FF0000";
            console.log(this.bmss.soc + "Red" + `v${i}0`);
          }
        }
        console.log(this.bmss.soc);
      },
    };
    </script>

Answer №1

Your approach seems to have a flaw where you are using the id html attribute for styling, which may result in non-unique ids when dealing with multiple batteries.

Instead of manipulating styles through id, it would be more appropriate to use the Style directive.

I have resolved the issue and made some improvements in the code structure.

Check out the updated code here

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

Is there a problem with the alignment of

<s:form id="inputThresholdForm" name="inputThresholdForm" theme="simple"> <table border="0" class="display-table" cellspacing="2" cellpadding="2" height="100%" width="100%"> <tr> <td colspan= ...

The ng-view in index.html is not being loaded by AngularJS

I've been working on setting up a single-page application using AngularJS. In my setup, I'm using Node with Express and have an Apache server functioning as middleware. The issue I'm facing is that while my index.html page loads without any ...

Oops! Vue.js is throwing a compile error involving unused variables and undefined variables

I'm currently working on developing a new Vue.js component, but I'm encountering an error when launching the application. The specific error message is displayed below: https://i.sstatic.net/0MQxl.png <template> <div class="hello" ...

reinitializing an array duplicate within an angular function following the use of .splice()

My goal is to create a dropdown menu in Angular that automatically removes the current page from the list when navigating to another view. I want the menu to reset and remove the now-current view every time a new view is loaded. This is the array of objec ...

AngularJS redirection causes the previous template to quickly appear and then disappear

This particular question has been circulating without a satisfactory resolution for some time, so hopefully the information provided here will help clear up any confusion. Essentially, I have an object called resolve attached to my routes, set up like thi ...

There was an error that said: "Uncaught TypeError: Function.prototype.apply: Arguments list has wrong type

I keep encountering the error Uncaught TypeError: Function.prototype.apply: Arguments list has wrong type whenever I utilize the .apply() method but I'm unable to pinpoint the cause. You can review my code here. Upon loading jsfiddle, try clicking ne ...

Custom sorting in JavaScript

I have a specialized sorting method that is defined as follows sortArrayBy: function(a, b, sortKey) { if (a[sortKey] < b[sortKey]) return -1; if (a[sortKey] > b[sortKey]) return 1; return 0; }, I am looking to enhance it ...

What could be causing an issue with CORS in ExpressJS in one scenario but not in another?

I am currently in the process of setting up a database and connecting it to various routes. Interestingly, I have been successful with one route ('register') but encountering issues with another ('login'). Whenever I attempt to run the ...

How come when I click on the edit button, the selected data's model doesn't appear in the dropdown menu as I would like it to?

this is the function in my controller public function getModel($make_id = null) { $make_id = request()->make_id; $carsmodel = CarModel::where('make_id', $make_id)->orderBy('model', 'ASC')->get(); return re ...

Ways to insert script tag in a React/JSX document?

private get mouseGestureSettingView() { const {selectedMenu} = this.state; return ( selectedMenu == 2 ? <script src="../../assets/js/extensions/mouse-gesture/options.js"></script> <div className={styles.settingForm}& ...

Ways to merge two select options in a form

I'm attempting to merge the selections from two dropdown menus in a form into one variable before submitting the form. Here is an overview of my code: In new.html.erb (for RoR): <%= form_for :character, url: characters_path, method: :post do |f| ...

Patience is key when waiting for both subscriptions to be completed before proceeding with an

I am facing a challenge with two subscriptions as shown below: this.birthdays = await this.birthdaySP.getBirthdays(); this.birthdays.subscribe(groups => { const allBirthdayT = []; groups.map(c => { allBirthdayT.push({ key: c.pa ...

Content will not render when JavaScript generates SVGs

As I delve into the world of JavaScript and SVG to create interactive graphics for a website, I've run into a puzzling issue with programmatically generated SVG paths not being drawn. Below is a sample code that highlights this problem: <!DOCTYPE ...

Using JQuery, retain only the initial N elements in a list and discard the rest

I'm looking to streamline a list of items in the DOM by keeping only the first N items, ideally through the use of slice and remove methods. Could someone provide me with the JQuery syntax for removing items that come after the first N in the list? ...

The animation-play-state is set to 'running', however, it refuses to start playing

I'm in the process of creating a landing page that includes CSS animations, such as fade-ins. Initially setting animation-play-state: "paused" in the CSS file, I later use jQuery to trigger the animation while scrolling through the page. While this s ...

Leveraging Vue Data for Storing CSS Properties

I am currently utilizing the Quasar framework in conjunction with Vue for my application development. Below is a snippet of my code: <q-tooltip content-class="bg-amber text-black shadow-4" :offset="[10, 10]"> Save </q-tooltip> <q-tooltip c ...

retrieve the value of a text form using jQuery and its corresponding id

I need help with a basic HTML form that includes jQuery. My goal is to: 1) Retrieve the value into a JavaScript variable. 2) Send it as JSON to a server. Here is the form: <div data-role="main" class="ui-content"> <data=role "form" ...

Global Vue Component Styles Seeping Through Entire Website Interface

By "Leaking", I mean the following scenario. I have an About.vue file with its own styling (About.scss) and endpoint "/about". Additionally, I have the home page endpoint "/" and its corresponding Laravel blade template (Index.blade.php) with its own styli ...

What is the best way to implement complex input filtering in JavaScript?

Is it possible to filter input content in this format? The input should accept 16 characters, separated into 4 groups by ":" like this: 0123:0055:02AC:01FA I divided them into 4 groups for later use, but I want to set a filter with the minimum value bei ...

Calculate the result by multiplying each row value with the value provided as input

Check out this HTML code snippet <form><input type="number"></form> <table class="my-table"> <thead> <tr> <td>Header 1</td> <td>Header 2</td> </tr> </thead> &l ...