如何解决更改子组件内部 props 创建的数组元素也会影响父组件的 props | Vuejs 3
我有一个父组件(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)
}
},...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。