我有一个父组件(App),其中有一个对象数组。我将此数组作为道具传递给子组件(UserLocations)。现在在子组件中,我使用这个数组并创建一个数据变量。
那么如果我要更改数组的一个元素,那么为什么父组件的属性也会更改。
App.Vue
<template>
<user-locations :initalLocations="locations"/>
</template>
<script>
import UserLocations from './components/UserLocations.vue'
export default {
name: 'App',
components: {
UserLocations
},
mounted() {
},
data: function() {
return {
locations: [
{"id": 121, name: "test 121", "order": 1},
{"id": 122, name: "test 122", "order": 2},
{"id": 123, name: "test 123", "order": 3},
{"id": 124, name: "test 124", "order": 4}
]
}
}
}
</script>
UserLocations.vue
<template>
<ul>
<li v-for="(location) in locations"
:key="location.id"
>
<span @click="decreaseOrder(location)">Up</span>
{{ location.name}} {{location.order}}
<span @click="increaseOrder(location)">down</span>
</li>
</ul>
</template>
<script>
export default {
data: function() {
return {
locations: [...this.initalLocations]
}
},
props: {
initalLocations: {
type: Array,
},
},
// computed: {
// locations() {
// return [
// ...this.initalLocations
// ]
// }
// },
methods:{
increaseOrder(location) {
if (location.order != this.locations.length) {
this.locations = this.locations.map(l => {
var returnLocation = {...l};
if (l.id == location.id) {
l.order += 1
}
return returnLocation
});
}
},
decreaseOrder(location) {
if (location.order != 1) {
this.locations = this.locations.map(l => {
var returnLocation = {...l};
if (l.id == location.id) {
l.order -= 1
}
return returnLocation
});
}
},
}
}
</script>
如您所见,我使用
initalLocations
属性在 UserLocations 组件内创建位置属性,当我通过单击向上/向下按钮更改数组的对象之一时,它会更改传递给 UserLocations 的属性而不是更改本地数据“位置”
扩展运算符不会深入克隆数组,您需要一个克隆数组而不是引用数组的函数:
<script>
function deepCopy(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
if (obj instanceof Array) {
return obj.reduce((arr, item, i) => {
arr[i] = deepCopy(item);
return arr;
}, []);
}
if (obj instanceof Object) {
return Object.keys(obj).reduce((newObj, key) => {
newObj[key] = deepCopy(obj[key]);
return newObj;
}, {})
}
}
export default {
data: function() {
return {
locations: deepCopy(this.initalLocations)
}
},
...