In Vue.js, dynamically rearrange the order of items in an Array and reflect that reordering in the Document Object Model

Within a Vue component, I have an Array named "block" that contains 4 values. These values are displayed in the DOM using a v-for directive:

<div class="block" @click="shuffleArray()">
    <div v-for="(number, index) in block">
        <span :class="[`index--${index}`]">{{ number }}</span>
    </div>
</div>

This code generates a div with 4 spans inside, each assigned a class of "index--0", "index--1", and so on.

When the div is clicked, the order of the values in the Array changes:

shuffleArray: function() {
    const shifted = this.block.shift();
    this.block.push( shifted );
}

Despite the values changing, they do not visually rearrange within the actual DOM. Is there a way to make the spans change position in the DOM when clicked? Each span has a unique background color applied to it, so a visual representation of the order change is desired:

span.index--0 {
    background-color: tomato;
}

span.index--1 {
    background-color: khaki;
}

span.index--2 {
    background-color: lavenderblush;
}

span.index--3 {
    background-color: lightcoral;
}

It would be great if there was a CSS-only solution that does not involve manipulating the DOM directly.

Answer №1

If you want to add a touch of elegance, I suggest utilizing the list transition feature:

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#list-demo',
  data: {
    items: [1,2,3,4,5,6,7,8,9],
    nextNum: 10
  },
  methods: {
    randomIndex: function () {
      return Math.floor(Math.random() * this.items.length)
    },
    add: function () {
      this.items.splice(this.randomIndex(), 0, this.nextNum++)
    },
    remove: function () {
      this.items.splice(this.randomIndex(), 1)
    },
  }
})
.list-item {
  display: inline-block;
  margin-right: 10px;
}
.list-enter-active, .list-leave-active {
  transition: all 1s;
}
.list-enter, .list-leave-to /* .list-leave-active below version 2.1.8 */ {
  opacity: 0;
  transform: translateY(30px);
}
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="list-demo">
  <button v-on:click="add">Add</button>
  <button v-on:click="remove">Remove</button>
  <transition-group name="list" tag="p">
    <span v-for="item in items" v-bind:key="item" class="list-item">
      {{ item }}
    </span>
  </transition-group>
</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

Jest is throwing an error: Unable to access property from undefined while trying to import from a custom

I developed a package called @package/test. It functions perfectly when imported into a new, empty React TypeScript application. However, issues arise within Jest test suites. The usage of the CommonJS package version causes Jest to throw an error: Test ...

Issues with form inputs alignment in Bootstrap 4 styling

Check out this sample jsFiddle I created, using the html directly from my website. The css for bootstrap 4 is included, which I compiled using sass in addition to my custom css. Everything seems to align perfectly on all screen sizes, except for small dis ...

Tips on preventing a partial hit in codecov when using a ternary assignment

I'm working with a vue function that returns an array of strings 1 selectStyles (): string[] { 2 const baseStyles = ['selected-label', 'px-4'] 3 const placeholderStyle = this.internalValue?.length === 0 ? 'text-gray-400&apos ...

Increment and decrement the like count on fa-heart multiple times

Is there a way to increment the count of a fa-heart value on click and decrement it on the second click? The issue I'm facing is that I have multiple fa-heart elements on the same page, making it challenging to increment or decrement the clicked fa-h ...

How can you convert a JavaScript object with nested arrays into JSON format?

I have been working with a JavaScript object that contains nested objects with associative arrays. I attempted to use the stringify function from the json2.js library, but the output did not include the arrays inside the nested objects. In my scenario, I b ...

Explore the possibilities of Vue by searching through an array of APIs in

As a newcomer to Vuejs, I am currently working on a web app that retrieves images from the Flickr API and stores them in an array. I want to implement a basic search functionality that allows users to filter images based on the keyword entered, but I am un ...

Show the entire phrase within a Bootstrap modal with the help of jQuery, instead of just the initial

I have a PHP script that fetches a name from a database, and I'm using jQuery to display that name as HTML inside a Bootstrap modal when a button is clicked. However, the issue I'm facing is that when the name contains spaces, only the first word ...

What causes json.parse to malfunction? and how can you resolve the issue

My server sends data to my JavaScript code in the format below. {"triggers": [{"message_type": "sms","recipients": "[\"+91xxxxxxxxx\",\"+91xxxxxxxxx\"]", "message": "This is a test"}]} To parse this JSON string, my code executes the f ...

I am encountering errors when running NPM start

After setting up my webpack, I encountered an error in the terminal when attempting to run the code npm start. The specific error message was related to a module not being found. Can someone please assist me with resolving this issue? > <a href="/c ...

The div element's width does not match the width of the textbox

I attempted to implement the following code in HTML. However, I am puzzled as to why the text box and div width are not the same size. Here is what I have experimented with. <style> .test { border:1px solid red;width:100px;height:30px;padding:3p ...

A method to find the sum of the final n elements in an array by employing Arr.reduceRight

I have successfully calculated the sum of the last n elements in an array using a for loop. Is it possible to achieve the same result using Arr.reduceRight instead? x = [1,2,3,4,5]; y = 0 for(let i=x.length; i>x.length-3; i--) { console.log(x[i-1]); ...

The API is only returning three records, but the backbone collection is not syncing up with

I am working with an API that provides a JSON object of "Groups". Below is the PHP code for this: public function index() { $teams = new Team; $clients = new Client; $organisations = new Organisation; // Get the organisations $org = O ...

Sorting through JSON information based on specific attributes and criteria

Consider this JSON object: { 'name' : 'John', 'friends' : [ { 'id' : 1, 'name' : 'George', 'level' : 10 }, { 'id' : 2, 'name ...

The markers within a loop in react-native-maps are failing to render

Recently, I've been delving into the world of React Native app development for iOS. Specifically, I've been experimenting with the react-native-maps package. Here's the issue I'm facing: When I statically render a single MapView.Marker, ...

Stop a user from adding duplicate tasks

I have developed a JavaScript code for creating a todo list. Currently, I am working on the phase of adding tasks to the list. The user wants to ensure that if a task is entered once, it cannot be entered again. const taskInput = document.getElementById(&a ...

The People and Groups selection dialog is displaying incorrectly in IE 10

I've been working on a Sharepoint web application and have created a site column of type “People or Group”. This should be automatically associated with a user selection dialog as shown below: However, as you can see in the image above, the users ...

Filter feature malfunctioning in Select2

My dropdownmenu is implemented using Select2 and is populated via an Ajax call to PHP, which retrieves data from MySQL. In the search field of the Select2 dropdownmenu, the letters I type get underlined but the filter functionality does not work. As a res ...

Is it necessary to send form data back with Express, or is there an alternative solution?

I am facing a simple problem with my handlers for /login get and post requests. Here is the code: loginRender(req, res) { let options = { title: 'Login', layout: 'auth.hbs' } res.render('login', options) } logi ...

Once the "Get Route" button is pressed, I want to save my JavaScript variable into a database

I am seeking to automatically extract data from the Google Maps API and store it in my MySQL database. Specifically, I want details such as source address, destination address, distance, and duration for all available routes to be inserted into my database ...

tips for storing user input into an array

I am currently developing a calculator that uses Json data. The goal is to retrieve the Grid Code associated with a specific longitude and latitude input. However, I am encountering an issue where the result returned is 0, indicating that the value of the ...