Updates to Vue.js data are not being properly reflected in the template

This is my unique text

<template>
  <div class="unique_class">
    <div class="unique_wrapper">
        <div v-for="(h, index) in heights" :key="index" class="each_bar" v-bind:style="{ height: h + 'px' }"></div>
    </div>

    <div class="unique-buttons">
        <button @click="resetArray">Reset</button>
        <button @click="bubbleSort">Bubble Sort</button>
        <button @click="sort">Sort</button>
    </div>
  </div>
</template>

Here's the script

export default {
    name: 'UniqueComponent',

    data() {
        return {
            heights: [],
            totalBars: 100,
        }
    },

    methods: {
        getRandomInt(min, max) {
            min = Math.ceil(min);
            max = Math.floor(max);
            return Math.floor(Math.random() * (max - min + 1)) + min;
        },

        resetArray() {
            this.heights = [];
            for(let i=0; i<this.totalBars; i++) {
                this.heights.push(this.getRandomInt(2, 400));
            }
        },

        bubbleSort() {
            for(let i=0; i<this.heights.length; i++) {
                for (let j=0; j<(this.heights.length-i-1); j++) {
                    if(this.heights[j]>this.heights[j+1]) {
                        let temp = this.heights[j];
                        this.heights[j] = this.heights[j+1];
                        this.heights[j+1] = temp;
                    }
                }
            }
            console.log(this.heights);
        },

        sort() {
            this.heights.sort((a, b) => a-b);
            console.log(this.heights);
        },
    },

    mounted() {
        for(let i=0; i<this.totalBars; i++) {
            this.heights.push(this.getRandomInt(2, 400));
        }
    },
}

I have encountered an issue where clicking the sort button correctly updates the template as expected, but when I click the bubbleSort button, although the heights are sorted in the console, the changes are not reflected in the template. Can anyone assist me with resolving this issue?

Answer №1

For adjusting values in an array, consider using Vue.set.

Vue.set(this.heights, j, this.heights[j+1]);
Vue.set(this.heights, j+1, tmp);

Alternatively, create a duplicate of the array, sort it, and then assign it to this.height. This method is also effective.

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 way to showcase the array data of two description values in a Vue v-for loop?

An array called ledgerDetails contains 32 data elements. These details are displayed in a vue v-for loop. However, within the loop, I need to show specific details from invoiceDescriptions (23 data elements) and paymentDescriptions (1 ...

What is the best way to set checkboxes to default values using a model?

My journey with angular.js continues as I embark on creating my first non-tutorial web app. In this endeavor, I am utilizing two smart-tables and checklist-model for a seamless user experience. The initial table uses a st-safe-src of all_types, containing ...

You are unable to call upon an object that may be undefined

I am using TypeScript in conjunction with React, and I keep encountering an error message. Cannot invoke an object which is possibly 'undefined'.ts(2722) const onChange: ((...args: any[]) => any) | undefined The errors occur in the following ...

Retrieve information from arrays within objects in a nested structure

I am working with structured data that looks like the example below: const arr = [{ id: 0, name: 'Biomes', icon: 'mdi-image-filter-hdr', isParent: true, children: [{ id: 1, name: 'Redwood forest& ...

What is the best way to selectively create transparency for a specific color in a three.js canvas?

I'm working with a three.js canvas that I generated using liquidfun.js. However, I'm encountering an issue where the canvas is not transparent. I want to make a specific color in the canvas fully transparent, such as the whitish background. Is t ...

What is the best way to configure maxSockets in Node.js while working with Express?

Can the maximum number of sockets in Node.js be adjusted while working with the Express framework? More information can be found here. ...

Tips for positioning text on the left and right sides of a div in HTML styling

I am struggling with positioning two pieces of text within a div. Despite having some styling already in place, the text is currently displaying one after the other on the left-hand side. I want to position one piece of text to the left and another to the ...

Tips for automatically redirecting a webpage to another webpage upon submission of form elements:

I'm currently working on a website where I want to integrate radio buttons as part of a form. Below is the code snippet I've been using... <form action="glitter.php" method="post"> <input type="radio" name="font" value="fonts/darkcrysta ...

Customizing CSS according to specific URLs

I have two different domains - one ending with .nl and the other ending with .be. For instance, domain.nl and domain.be. Both domains share a similar overall style, but I want certain elements to have distinct styling depending on whether it is the .nl o ...

Is it possible to use a variable in JSX within a map function to modify inline CSS styles?

I have a map function that loops through an array and generates divs on the DOM for each color item. The array consists of hex values representing different colors (e.g. #1a703f). The goal is to set the background of each div to match the corresponding co ...

The drag functionality can only be used once when applied to two separate div elements

Recently, I came across an issue where I have both an Image and a custom text element placed between them using an input box. My goal is to make both the text and the image draggable on the page. However, I noticed that while the image can be dragged and d ...

Storing data with NPM global packages: Best practices

I have developed a global npm package that functions as a CLI tool. https://i.sstatic.net/PdT3Z.png My goal is to customize the user experience by having the package remember the user's previous choices. For example, if the user selects 'Iphone ...

Integrating XML API Requests Using HTML and JavaScript

When there is only one item in the XML document, I want to update my inner HTML with the result of an API call. I have managed to successfully make the API call work when there are multiple items in the XML document (thanks to W3). <!DOCTYPE html> ...

Personalized verification script using bootstrap

I'm struggling with implementing form validation in my bootstrap form. I specifically want to use a regex pattern that only allows alphabets in the name field. However, my validation doesn't seem to be working. Can anyone help me identify the iss ...

Is there a way to sort through nested objects with unspecified keys?

I'm looking to extract specific information from a nested object with unknown keys and create a new array with it. This data is retrieved from the CUPS API, where printer names act as keys. I want to filter based on conditions like 'printer-stat ...

Implementing NgRx state management to track and synchronize array updates

If you have multiple objects to add in ngrx state, how can you ensure they are all captured and kept in sync? For example, what if one user is associated with more than one task? Currently, when all tasks are returned, the store is updated twice. However, ...

You cannot add properties to an object within an async function

I am attempting to include a fileUrl property in the order object within an async function, but I am unable to make it work properly. My expectation is for the order object to contain a fileUrl property once added, but unfortunately, it does not seem to b ...

What would the equivalent Javascript implementation look like for this Python code that decodes a hex string and then encodes it to base64?

Currently, I am facing the challenge of transferring code from a Python script that decodes and encodes a string using a series of decode() and encode() functions. In Python, the code appears as follows: import codecs input = '3E061F00000E10FE' ...

Troubleshooting Next.js server actions with ESLint error detection

I encountered eslint errors while developing a basic server component with server action: // /app/search/page.tsx export default function Search() { async function updateResults(formData: FormData) { "use server"; await new Promise((r ...

Saving JSON format in VueX State Management

I'm relatively new to using Vue/VueX and I am exploring methods for storing JSON data in the VueX state. Initially, it seemed like a simple task: state { jsonthing: { ... } } However, I encountered an issue where getters return an Observer type ins ...