简体   繁体   English

数组:如何根据索引更改特定值(评级函数)

[英]Array: How to change specific values dependent on index (Rating function)

I'm sorry for the terrible title, but somehow I can't explain it better in one sentence.对于糟糕的标题,我很抱歉,但不知何故,我无法用一句话更好地解释它。

What I want to do is a rating component in my Vue App.我想要做的是在我的 Vue 应用程序中添加一个评级组件。 So if I click the 3rd star, the two stars before that one are set to "true" as well.因此,如果我单击第三颗星,那颗星之前的两颗星也将设置为“真”。

What I got:我得到了什么:

const ratingsArray = [
  {
    name: 'rating1',
    ratingCount: 1,
    isClicked: ref(false)
  },
  {
    name: 'rating2',
    ratingCount: 2,
    isClicked: ref(false)
  },
  {
    name: 'rating3',
    ratingCount: 3,
    isClicked: ref(false)
  },
  {
    name: 'rating4',
    ratingCount: 4,
    isClicked: ref(false)
  },
  {
    name: 'rating5',
    ratingCount: 5,
    isClicked: ref(false)
  },
]

I just got a toggle function to toggle isClicked :我刚得到一个切换 function 来切换isClicked

function toggleClick(x) {
  x.value = !x.value
}

This is my template这是我的模板

<template>
    <div v-for="rating in ratingsArray" 
     :key="rating.name" 
     @click="toggleClick(rating.isClicked)" 
     :class="[rating.isClicked.value ? 'ratingBoxFilled' : 'ratingBox']">
    </div>
</template>

How can I say, that if rating3 is clicked (so isClicked is true), rating1 and rating2 also got to be true?我怎么能说,如果点击了rating3 (所以isClicked为真),那么 rating1 和 rating2 也必须为真?

It seems that I need to work with the index in my array.看来我需要使用数组中的索引。 But somehow, I cannot create an idea.但不知何故,我无法创造一个想法。 Maybe you guys can help me out.也许你们可以帮助我。 Thank you!谢谢你!

A simple loop would do the trick:一个简单的循环就可以解决问题:

<template>
    <div v-for="(rating, index) in ratingsArray" 
     :key="rating.name" 
     @click="toggleClick(index)" 
     :class="[rating.isClicked.value ? 'ratingBoxFilled' : 'ratingBox']">
    </div>
</template>

function toggleClick(ratingIndex) {
  for (let i = 0; i < ratingsArray.length; i++) {
    // Set ratingsArray[i].isClicked to true if it's within the requested range
    ratingsArray[i].isClicked.value = (i <= ratingIndex);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM