`Shuffle the order of Vue.js elements upon page load for a randomized effect`

I need help targeting specific elements using the ref attribute in Vuejs to randomize their order every time the page loads.

The data is displayed in the template and managed in the component:

<div class="team" >
  <div class="team__card" ref="card" v-for="(member, index) in team"
  :key="index">
  <div v-for="(image, imageIndex) in member.image" :key="imageIndex">
    <img :src="image" alt="Photo of team member" :key="imageIndex" />
  </div>
  <div class="team__card-content">
    <p class="font-bold text-xl">{{ member.name }}</p>
    <p class="font-bold text-gray-700">{{ member.title }}</p>
    <p class="text-gray-700">{{ member.description }}</p>
  </div>
 </div>
</div>

<script>
export default {
name: 'Page Name',
data() {
 return {
  team: [
   {
     image: [require('url')],
     name: 'Name',
     title: 'Title',
     description:'description.'
   },
   {
     image: [require('url')],
     name: 'Name',
     title: 'Title',
     description:'description.'
   },
  ]
 }
},
created() {
    this.randomize()
  },
  methods: {
    randomize() {
      for (let i = this.team.length - 1; i > 0; i--) {
        let randomIndex = Math.floor(Math.random() * i)
        let temp = this.team[i]
        this.set(this.team, i, this.team[randomIndex])
        this.set(this.team, randomIndex, temp)
      }
    }
  }
}
</script>

Can anyone provide some insight on how to shuffle/randomize the order of my card elements on each page load? Thanks in advance!

Answer №1

The addSet function is missing a # before set. Without the #, it will result in a runtime error indicating that set is not defined.

addSet(team, i, team[randomIndex])
addSet(team, randomIndex, temp)

Alternatively, you could use Vue.add; however, because set is being called within a function that has access to a Vue instance, it is recommended to use addSet.

Here is a working example:

https://codesandbox.io/s/eager-cori-cu75f

Answer №2

It's not recommended to directly manipulate the DOM in Vue because the changes may be overridden during the next update cycle, potentially causing confusion for Vue.

Instead of hardcoding cards in the template, consider defining the card data in an array within the component's data property. You can then use v-for to render the cards and easily shuffle the array.

Check out this demo for an example:

// Here's a function to shuffle an array in place, compatible
// with Vue's reactivity system
function shuffleVueArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    const temp = array[i];
    Vue.set(array, i, array[j]);
    Vue.set(array, j, temp);
  }
}

new Vue({
  el: '#app',
  data: {
    items: [
      'apple',
      'banana',
      'orange',
      'pear',
      'pineapple',
      'mango',
    ],
  },
  methods: {
    randomize() {
      shuffleVueArray(this.items);
    },
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button @click="randomize">Randomize</button>
  <ul>
    <li v-for="item of items">{{ item }}</li>
  </ul>
</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

In CodeIgniter, when there are multiple entries with the same ID in a foreach loop, the elements can be summed

I am using a foreach loop to create a table with data from the "sale" row, specifically json_decode($row['sale']). Currently, each entry is being displayed separately. However, my goal is to display entries with the same id [product_id] as one ro ...

Interactive Thumbnail Previews

There seems to be an issue with the thumbnail links on my page. The leftmost and rightmost links work fine, but the middle ones are not functioning properly when clicked. The PHP code used to generate these links is the same for all of them, so it's p ...

Guide on Implementing jQuery Plugin with Vue, Webpack, and Typescript

I am currently exploring the integration of the jQuery Plugin Chosen into my vue.js/Webpack project with TypeScript. After some research, I discovered that it is recommended to encapsulate the plugin within a custom Vue component. To kick things off, I m ...

What is the best way to maintain the current position in a component while interacting with another component?

I have a component that displays a collection of cards with images. There is a button that toggles between showing another component and returning to the original list of cards. The issue I am encountering is that every time I return to the list of cards, ...

Changing the background image within a CSS class on an imported Vue component

Is there a way to dynamically change the background-image on a CSS class within an imported component? I have successfully installed 'vue-range-slider' and imported RangeSlider. The setup for the range-slider is as follows: <template> ...

The state variable remains undefined even after integrating useEffect in a React.js component

Hello, I have a component within my React application that looks like this: import React, { useEffect, useState } from "react"; import AsyncSelect from "react-select/async"; import { ColourOption, colourOptions } from "./docs/data"; const App = () => ...

Ensuring form input validity in real-time using jQuery's keyup event

I've been working on a form where the user can fill in an input and press enter to move to the next field. Although I have managed to get the functionality to show the next div, I am facing issues with validation... // Moving to next div on Enter ...

Netlify Lambda function with Expressjs generates a fresh session for each incoming request

Good Evening, After successfully running my Expressjs API locally without utilizing lambda functions, I encountered an issue where every request created a new session once the lambda function was introduced. Below is the implementation of server.js and Das ...

Is there a way to duplicate a GLTF model that has been imported into the Autodesk Viewer?

I encountered an issue while trying to dynamically clone a loaded GLB model and allow the user to position it in the scene. Despite using the model.clone() method, the cloned model ends up appearing at the same position as the original, causing changes in ...

Exploring the Ways to Share sessionStorage Across Multiple Browser Tabs Using JavaScript

I have recently started exploring client-side data storage and have successfully implemented an onkeyup search function. The goal is to retrieve the city name via AJAX and display it at the top within the header of the page. To store the city name, I have ...

Generating matrices in MATLAB

Is there a way to create an array in Matlab that allows me to store multiple user inputs without replacing the previous ones? As a beginner, I appreciate your patience with me. Thank you! ...

"Efficiently storing huge amounts of data in MySQL in just 5

Interested in my tech stack: express + typeorm + mysql Seeking a solution for the following task: I have a csv file with over 100000 rows, where each row contains data such as: reviewer, review, email, rating, employee, employee_position, employee_unique_ ...

JavaScript Conversion of Characters to ASCII Values

After converting a string input into a split array, I now need to convert that split array into ASCII for evaluation. Can someone provide guidance on how to do this? ...

Breaking an array in JavaScript

I'm developing a pure JavaScript hangman game and facing an issue with splitting words from an array into single letters. When I split the array, I get "," for every letter. For example, when I split the word [station], it returns "s,t,a,t,i,o,n". M ...

ASP.NET - The Power of a Long Press

I am currently working on implementing a Long Press event in JavaScript on an ASPX page. Due to my limited experience with JavaScript, I am facing a few challenges. I found a similar question that was previously asked here. When running the code, I encoun ...

Tips for keeping JavaScript created checkboxes saved and accessible

Utilizing the "ajax" function within the script enables communication with the server by sending post or delete messages. The javascript code that includes ajax is responsible for dynamically adding checkboxes to the page. How can we ensure that the create ...

Error in TypeScript - Anticipated 1-2 arguments, received either none or multiple. Code Issue TS2556

While working in JavaScript, I had no issues with this code snippet. However, when I attempted to implement it in a TypeScript Project, an error surfaced. The problem seems to revolve around the fetch(...args) function call. const fetcher = (...args) =&g ...

Implement currency formatting in input text with v-model in Vue

Is there a way to add a currency sign to the input value in such a way that it appears as part of the input itself? For example, how can I make it display "10 $" when the user inputs 10 while still keeping "10" as the actual data value of amount? input( ...

Despite using Vue and Vuex with Axios asynchronously, the getters are still returning an empty array

I am encountering an issue with getters that are returning the initial state (an empty array). In my component, I have a method called created that sets the axios call result into the state. created() {this.$store.dispatch("SET_STORIES");}, I am using m ...

Elevating the mesh causes the ray caster to perceive it as though it has been flipped along the Y-axis

My raycaster seems to be detecting all my objects but in a flipped manner. It works fine when I add a cube without changing its position, but as soon as I move the cube up, the ray-casting goes downwards. Does anyone have a solution for this issue? Curren ...