我有三个v-select,可以在其中选择某些值。所有这些都应该是唯一的(而不是在下拉菜单中)。我有三个数组。第一个使下拉列表中的值始终显示相同(此数组对函数不重要)。第二个在v模型的帮助下绑定到相应的下拉列表。第三是在那里认识到我必须交换什么价值,以便所有价值保持唯一。奇怪的是,函数第一次运行,但是第二次更改了第三个数组,就像第二个数组一样,这是通过v模型绑定的(完全相同)。但是,我在任何地方都更改了第三个数组的值,函数中除外。
<template>
<div>
<v-select
v-model="selectedCollections[0]"
:items="collections"
label="1. Collection"
@change="uniqueCollections(0)"
/>
<v-select
v-model="selectedCollections[1]"
:items="collections"
label="2. Collection"
@change="uniqueCollections(1)"
/>
<v-select
v-model="selectedCollections[2]"
:items="collections"
label="3. Collection"
@change="uniqueCollections(2)"
/>
</div>
</template>
<script>
export default {
props: {
id: {
type: [String],
default: ''
}
},
data () {
return {
collections: [
"Playlist",
"Screen",
"Location"
],
selectedCollections: [
"Playlist",
"Screen",
"Location"
],
selectedStaticCollections: [
"Playlist",
"Screen",
"Location"
]
}
},
methods: {
uniqueCollections: function (index) {
var before = this.selectedCollections[index]
var indexList = this.selectedStaticCollections.indexOf(before)
var temp = this.selectedStaticCollections[index]
this.selectedStaticCollections[index] = this.selectedStaticCollections[indexList]
this.selectedStaticCollections[indexList] = temp
this.selectedCollections = this.selectedStaticCollections
}
}
}
</script>
为什么第二次调用函数时第三个数组改变了?
答案 0 :(得分:0)
正如我在您的函数中所看到的,您正在将array
分配给array
。数组在JS中为objects
,其行为不像primitives
。分配后,如果两个数组中的任何一个都进行了更改,则两个数组都将更改。
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
arr1 = arr2;
arr2[2] = 999;
console.log(arr1[2]); // Will also log 999
如果要复制值但不引用数组,则可以使用Array.from()
方法:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
arr1 = Array.from(arr2);
arr2[2] = 999;
console.log(arr1[2]); // Will log 6