我如何在vue.js中映射数组

问题描述

我正在使用Vue和anime.js处理代码。我发现我的代码太长,由1500多行组成。我在这里sampleText削减为5个项目,因此Stack Overflow将接受我的问题,但实际上是114个项目。

我又如何将sampleText随机放入<li>中?它应该在sampleText的每个位置拖曳<li>

<template>
  <div>
    <ul>
      <li>
        {{ texts.text1 }}
      </li>
      <li">
        {{ texts.text2 }}
      </li>
      <li>
        {{ texts.text3 }}
      </li>
      <li>
        {{ texts.text4 }}
      </li>
      <li>
        {{ texts.text5 }}
      </li>
    </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',update: scrambleText(sampleText2,'text2'),update: scrambleText(sampleText3,'text3'),update: scrambleText(sampleText4,'text4'),update: scrambleText(sampleText5,'text5'),})
    })

    return {
      texts,}
</script>

解决方法

您可以将所有文本放入一个数组中,然后像这样遍历它:

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

在所有文字都是唯一的条件下给出的键。

然后继续更改onMounted中的功能以执行以下操作:

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

这看起来像是数组和循环的好用例。

  1. 将示例文本放入array中,而不是对象,然后使用for-loop进行迭代。

  2. 更新scrambleText()调用以传递数组索引而不是先前用于对象的对象键:

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

onMounted(() => {
  for (let i = 0; i < texts.length; i++) { // 1️⃣
    anime({
      duration: 1000,easing: 'linear',update: scrambleText(texts[i],i),// 2️⃣
    })
  }
})
  1. 在模板中,使用v-for迭代texts数组:
<ul>
  <li v-for="text in texts">{{ text }}</li>
</ul>

demo