"What is the best way to manipulate arrays in vue.js using the map function

I'm currently dealing with a Vue code that incorporates anime.js. My code has grown substantially to over 1500 lines. In order for Stack Overflow to accept my question, I have only included 5 items of my sampleText, even though it actually consists of 114 items.

Furthermore, I am interested in understanding how I can randomly distribute the sampleText within each <li> element. The goal is to shuffle the sampleText within each <li> position.

<template>
  <div>
    <ul>
      <li>
        {{ texts.text1 }}
      </li>
      <li">
        {{ texts.text2 }}
      </li>
      <li>
        {{ texts.text3 }}
      </li>
      <li>
        {{ texts.text4 }}
      </li>
      <li>
        {{ texts.text5 }}
      </li>
     // more list elements...
    </ul>
  </div>
</template>

<script>
import anime from 'animejs/lib/anime.es.js'
import { reactive, onMounted } from '@nuxtjs/composition-api'

const sampleText1 = 'インバウント'
const sampleText2 = 'BtoB'
const sampleText3 = 'セールス'
const sampleText4 = 'OODA'
const sampleText5 = '指標'

const characters =
  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
const charactersLength = characters.length

export default {
  layout: 'default',
  data() {
    return {
      sam1: sampleText1,
      sam2: sampleText2,
      sam3: sampleText3,
      sam4: sampleText4,
      sam5: sampleText5,
    }
  },
  setup() {
    const texts = reactive({
      text1: sampleText1,
      text2: sampleText2,
      text3: sampleText3,
      text4: sampleText4,
      text5: sampleText5,
    })

    const scrambleText = (text, name) => ({ progress }) => {
      if (Math.floor(progress) <= 50) {
        if (Math.floor(progress) >= 50) {
          texts[name] = text
        } else if (Math.floor(progress) % 5 === 0) {
          texts[name] = text.replace(/./g, () =>
            characters.charAt(Math.floor(Math.random() * charactersLength))
          )
        }
      }
    }

    onMounted(() => {
      anime({
        targets: '.main',
        duration: 1000,
        easing: 'linear',
        loop: true,
        update: scrambleText(sampleText1, 'text1'),
      })
      anime({
        targets: '.main',
        duration: 1000,
        easing: 'linear',
        loop: true,
        update: scrambleText(sampleText2, 'text2'),
      })
      anime({
        targets: '.main',
        duration: 1000,
        easing: 'linear',
        loop: true,
        update: scrambleText(sampleText3, 'text3'),
      })
      anime({
        targets: '.main',
        duration: 1000,
        easing: 'linear',
        loop: true,
        update: scrambleText(sampleText4, 'text4'),
      })
      anime({
        targets: '.main',
        duration: 1000,
        easing: 'linear',
        loop: true,
        update: scrambleText(sampleText5, 'text5'),
      })
    })

    return {
      texts,
    }
  },
}
</script>

Answer №1

This situation calls for leveraging arrays and loops to optimize the process.

  1. To enhance efficiency, consider placing your sample text in an array and utilizing a for-loop to iterate over it.

  2. Revise the scrambleText() function call by passing the array index instead of the previously used object key:

const texts = reactive([ // 1️⃣
  'インバウント',
  'BtoB',
  'セールス',
  'OODA',
  '指標',
  //...
])

onMounted(() => {
  for (let i = 0; i < texts.length; i++) { // 1️⃣
    anime({
      duration: 1000,
      easing: 'linear',
      loop: true,
      update: scrambleText(texts[i], i), // 2️⃣
    })
  }
})
  1. To display the content from the texts array in your template, utilize a v-for directive:
<ul>
  <li v-for="text in texts">{{ text }}</li>
</ul>

Check out the demo here

Answer №2

If you gather all your written content in a collection and loop through it, the process can look like this:

<ul>
   <li v-for="text in texts" :key="text">{{ text }}</li>
</ul>

It is crucial to ensure that each piece of text is unique for proper indexing.

To proceed, consider adjusting the functions within the onMounted event to execute something similar to the following:

texts.forEach((text, index) => {
      anime({
        targets: ".main",
        duration: 1000,
        easing: "linear",
        loop: true,
        update: scrambleText(text, index),
      });
    });

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

A comparison of parent and child components

To implement a child-parent component relationship in Angular, first create two JSON files: parent.json and child.json. The parent.json file should contain the following data: "Id":10001, "name":"John" "Id":10002, ...

Leveraging and utilizing TypeScript npm packages

My goal is to create shared code in TypeScript, package it as an npm package, and easily install it. I attempted to create an external library like this: export class Lib { constructor(){ } getData(){ console.log('getting data from l ...

next-redux-wrapper is being invoked repeatedly and experiencing multiple calls to HYDRATE

I'm embarking on a new Next.js project, transitioning from a standard React app to a Next.js application. Our plan is to utilize Redux Toolkit for global state management and incorporate server-side rendering. During this process, we discovered the ne ...

Is there a method available to minimize the size of a local storage list containing strings?

Hey there, I am trying to load a large 2.5MB json file in my browser so that I can use it for some typeAhead functions. Unfortunately, I'm facing an issue with my local storage being constantly full. When using Firefox, I receive the following error ...

Encountered an issue with JSON serialization while using getServerSideProps in Next.js and TypeScript to retrieve products from the Stripe Payments API

Encountered Issue on Localhost Error: The error occurred while serializing .products returned from getServerSideProps in "/". Reason: JSON serialization cannot be performed on undefined. Please use null or exclude this value. Code Sample import ...

Troubleshooting ng-class functionality in AngularJS

I am attempting to utilize AngularJS in order to change the class name of a div element. Despite following the guidance provided in this answer, I am encountering difficulties as the class name is not updating in my view. Below is the code from my view: ...

Steps for setting up node-openalpr on a Windows 10 system

While attempting to install npm i node-openalpr, an error is occurring: When using request for node-pre-gyp https download, I encounter a node-pre-gyp warning and error message. The package.json for node-openalpr is not node-pre-gyp ready, as certain pr ...

Strategies for handling numerous node projects efficiently?

Currently, we are utilizing three distinct node projects: Project 1, Project 2, and Project 3 incorporating react and webpack. Each of these projects is stored in their individual repositories. While Project 1 and Project 2 operate independently, Project ...

What is causing the ESLint error when trying to use an async function that returns a Promise?

In my Next.js application, I have defined an async function with Promise return and used it as an event handler for an HTML anchor element. However, when I try to run my code, ESLint throws the following error: "Promise-returning function provided t ...

Float: A threshold reached when adding 1 no longer has any effect

In the realm of programming, float serves as an estimation of a numeric value. For example, 12345678901234567890 === 12345678901234567891 evaluates to true However, 1234567890 === 1234567891 yields false Where does the equation num === num+1 reach a br ...

Utilizing jQuery to fetch the source value of an image when the closest radio button is selected

On my website, I have a collection of divs that display color swatches in thumbnail size images. What I want to achieve is updating the main product image when a user clicks on a radio button by fetching the source value of the image inside the label eleme ...

Writing and altering content within the <code> element in Chrome is unreliable

Utilizing a WYSIWYG Editor with contenteditable functionality allows users to input "code snippets" using a <code> element. Here is an example: <div contenteditable="true"> <p> This is a paragraph with an <code>inline s ...

Is it possible to view the code within the .js files located in the api directory of NextJS using web browsers?

Is it possible to view the code of ".js files" in the "api folder" of NextJS using browsers? I came across a post on Stack Overflow where someone asked if Next.js API is back-end, and one of the answers stated: The back-end or server-side of Next.js res ...

The Wikipedia API is unable to be loaded using the XMLHttpRequest

I have encountered this error before on this platform, and although I managed to fix it, I am seeking a more in-depth explanation of the solution. For a project where I am learning, I decided to create a Wikipedia Viewer application. The first step was to ...

Using Angular to make a DELETE request using HttpClient with a Json Server

My goal is to remove one employee at a time from the Employees list. The Observable is configured in employee.service.ts and subscribed in app.component.ts. However, there seems to be an issue connecting the id of the employee with the removeUser(id) metho ...

Once the form has been submitted, proceed to open a new page following processing

Trying to remove an entry or offer from the database and then return to the page with all entries/offers. Attempted using Javascript, but it successfully deletes the item without redirecting to the overview page. Is this the correct approach with Javascri ...

The issue of unselection not functioning properly for multiple items when using both selectable and draggable features

i need the unselection of list items to be as smooth as selectable() but without draggable() My desired outcome is similar to the following gif showcasing combined selectable and draggable functionality: https://i.stack.imgur.com/3GjTD.gif here's t ...

Error 403: ACCESS DENIED - The server comprehended the inquiry, yet declines to carry it out

Encountering a persistent 403 error when making an AJAX call to an API. This issue is specific to Microsoft Edge, while other browsers like IE, Chrome, Firefox, and Safari work without any errors. The page doesn't utilize bootstrap, as there have be ...

Anchoring HTTP headers in HTML tags

Currently, I am working on some code to enable dragging files from a web app to the desktop by utilizing Chrome's anchor element dragging support. The challenge I am facing is that certain file links require more than a simple GET request - they nece ...

What categories do input events fall into within Vue?

What Typescript types should be used for input events in Vue to avoid missing target value, key, or files properties when using Event? For example: <input @input="(e: MISSING_TYPE) => {}" /> <input @keypress="(e: MISSING_TYPE) = ...