[英]Vue 2 - How to select multiple values from an array or object
With v-for
I display elements to the screen then using classes from vue js ( :class
) I present the ability to select certain elements by clicking on them使用v-for
我在屏幕上显示元素,然后使用来自 vue js 的类 ( :class
) 我通过单击某些元素来展示 select 某些元素的能力
The problem is that my plans have changed and now I need to make sure that the user can select as many elements as he wants, that is, at the moment you can select only one element when clicking on another element, the active class from the previous element is disabled now I need to select as many elements How many do you need.问题是我的计划已经改变,现在我需要确保用户可以 select 任意数量的元素,也就是说,目前你可以 select 当点击另一个元素时,只有一个元素,活动的 ZA2F2ED4F8EBC2CBBDZC2以前的元素被禁用现在我需要 select 尽可能多的元素 你需要多少。
Here is the given code in codesandbox这是codesandbox中的给定代码
<template>
<div>
<ul class="times-slot">
<li
v-for="(item, index) in TimeToChoose"
:key="index"
:class="{ 'selected-time': item === selectedTime }"
v-on:click="selectedTime = item"
>
{{ item }}
</li>
</ul>
</div>
</template>
<script>
let ts = require("time-slots-generator");
export default {
name: "HelloWorld",
data() {
return {
TimeToChoose: ts.getTimeSlots([], true, "half"),
selectedTime: "",
};
},
};
</script>
<style scoped>
.selected-time {
background: #CC003D;
border: 1px solid #FFFFFF;
color: white;
}
.times-slot {
display: flex;
align-items: center;
margin: 0;
padding: 0;
}
.times-slot li {
min-width: 70px;
border-radius: 7px;
border: #ffffff;
padding: 4px 0 4px 0;
}
.times-slot li:hover {
cursor: pointer;
}
li {
list-style-type: none;
}
</style>
You can use array to first define the selectedTime and them use push
and splice
to add or remove items.您可以使用数组首先定义 selectedTime,然后他们使用push
和splice
来添加或删除项目。
Update the template section as this:将模板部分更新为:
<ul class="times-slot">
<li
v-for="(item, index) in TimeToChoose"
:key="index"
:class="{ 'selected-time': selectedTime.includes(item) }"
v-on:click="selectedTime.includes(item) ? selectedTime.splice(selectedTime.indexOf(item), 1) : selectedTime.push(item)"
>
{{ item }}
</li>
</ul>
Update the data section:更新数据部分:
data() {
return {
TimeToChoose: ts.getTimeSlots([], true, "half"),
selectedTime: [],
};
},
if you have the ability yo create an object of each item which will contain the isSelected
property it will be the best way to achieve this:如果您有能力为每个项目创建一个包含isSelected
属性的 object,这将是实现此目的的最佳方法:
<li
v-for="(item, index) in TimeToChoose"
:key="index"
:class="{ 'selected-time': item.isSelected }"
@click="item.isSelected = !item.isSelected"
>
But if you have to use a different variable that holds your selected value you can save an array of selected items in the data, and add the clicked item to the array like so:但是,如果您必须使用保存所选值的不同变量,您可以在数据中保存一组选定项,并将单击的项添加到数组中,如下所示:
<li
v-for="(item, index) in TimeToChoose"
:key="index"
:class="{ 'selected-time': selectedItems.includes(item) }"
@click="selectedItems.push(item)"
>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.