I have a very specific question regarding Vue2 and Vue3 integration.
In my main project, I am using Vue2 and I have included my Vue3 web components project as an npm library. The issue I am facing is that when I pass an object as a property to the Vue3 web component from the Vue2 project and then make changes to that object (e.g., push a new value into an array), the watcher or computed property inside the Vue3 web component does not detect the change. The only way to see the change reflected is by copying the object, which is not ideal. Interestingly, when I use Vue3 for both projects, everything works perfectly fine.
Can someone provide assistance or explain why this behavior occurs?
Below is the code snippet for the Vue2 project where deep watching is implemented to detect changes:
<template>
<div>
<problem
:testObject.prop="testObject"
@testEmit="pushArray"
/>
{{ testObject }}
</div>
</template>
<script>
export default {
data()
{
return {
testObject: null,
};
},
created()
{
this.testObject = {
objectArray: [1, 2],
};
},
methods:
{
pushArray()
{
this.testObject.objectArray.push(5);
},
},
watch: {
testObject:
{
handler(newVal)
{
console.log('View watcher triggered', newVal);
},
deep: true,
},
},
};
</script>
And here is the code snippet for the Vue3 web component where watchers/computed properties are not detecting the prop change:
<template>
<div>
Prop Object {{ testObject }}
<hr>
Ref Object {{ objectWithArray }}
<br>
<button @click="pushArray">
Push array
</button>
</div>
</template>
<script lang="ts">
import {defineComponent, watch, computed} from 'vue'
export default defineComponent(
{
props: {
testObject: {
type: Object,
default: () => (null),
}
},
emits: ['testEmit'],
setup(props, ctx)
{
const objectWithArray: any = computed(() =>
{
console.log('Computed triggered');
return props.testObject;
})
const pushArray = () =>
{
ctx.emit('testEmit');
}
watch(
() => props.testObject,
(newVal) =>
{
console.log('Component watcher triggered', newVal);
},
{deep: true}
)
return {
pushArray,
objectWithArray
}
}
})
</script>