Reputation: 87
I have a parent component, which has a child component that has a child component. The parent passes data to the first child as a prop. What I want to do is to forward this prop to the second child, and then I want to compare the data in that prop with data in my second child, and if that data contains an identical result, then it needs to stop a method in the second child from running.
The problem is that just passing the prop from child 1 to child 2 causes a prop mutation warning.
The parent:
<template>
<div>
<child-one :my-data="myData"/>
</div>
</template>
<script>
data() {
return {
myData: [ some data... ]
}
}
</script>
Child one
<template>
<div>
<button @click="openModal">Open second child</button>
<child-two :my-data="myData" ref="openChildTwoModal"/>
</div>
</template>
<script>
props: { myData: Array }
methods: {
openModal() {
this.$refs['openChildTwoModal'].open
}
}
}
</script>
Child two
<template>
<div>
</div>
</template>
<script>
props: { myData: Array }
data() {
return {
showModal: false
myOtherData: [ some other data... ]
}
}
methods: {
open() {
this.showModal = true
}
checkIfSimilarIdExists() {
if (this.myData.some(data => data.id === this.myOtherData.id)) {
console.log('There is a duplicate ID!')
}
},
}
}
</script>
I tried creating a new variable in child one, where I could pass the data from the prop, so I wouldn't mutate it directly. Like:
mounted() {
this.newDataList = this.myData
}
but still getting the mutated prop error.
I was thinking of using emit, but then remembered that emit goes the opposite way from child two to child one to parent.
Why can't I pass the prop from child one to two?
Upvotes: 0
Views: 49
Reputation: 1136
Inside Child two
, you can use structuredClone, so that it won't mutate it's parent data.
Here's an example on child two
component, you can computed
to access the data like this:
<template>
<div>
{{ nonMutatedData }}
</div>
</template>
<script>
props: { myData: Array }
data() {
return {
showModal: false
myOtherData: [ some other data... ]
}
}
methods: {
open() {
this.showModal = true
},
checkIfSimilarIdExists() {
if (this.myData.some(data => data.id === this.myOtherData.id)) {
console.log('There is a duplicate ID!')
}
},
}
computed: {
nonMutatedData() {
const clonedData = structuredClone(this.myData)
return clonedData
}
}
}
</script>
Upvotes: 0