I want to pass reactive data object to child, but app shows blank page without error message whatsoever. I want to use composition api.
Parent:
<template>
<Landscape :viewData="viewData"/>
</template>
<script>
import { onMounted, onUnmounted, ref, inject } from 'vue';
export default {
name: 'App',
setup() {
const resizeView = ref(false)
const mobileView = ref(false)
const viewData = reactive({resizeView, mobileView})
viewData.resizeView.value = false
viewData.mobileView.value = false
// lets do sth to change viewData
return {
viewData
}
},
components: {
Landscape
}
}
</script>
Child:
<template>resize- {{viewData.resizeView}} mob {{viewData.mobileView}}
</template>
<script>
export default {
name: 'Header',
props: {
viewData: Object,
},
setup() {
return {
}
}
}
</script>
everything works, when in parent, data object is passed directy like this
<Landscape :viewData="{resizeView: false, mobileView: false}"/>
According to Vue docs about reactive objects:
The reactive conversion is "deep"—it affects all nested properties.
So you don't need to wrap every variable as a ref in reactive object (unless you want to unwrap ref variable). Check Vue docs for more info about reactivity API in Vue.
I provided some basic usage of ref and reactive with your Landscape component. Paste this in your App.vue:
<template>
<button @Click="changeResize" type="button">Change ref values</button>
<Landscape :viewData="viewData" />
<br />
<br />
<button @Click="changeReactiveSize" type="button">
Change reactive values
</button>
<Landscape :viewData="otherViewData" />
</template>
<script>
import { onMounted, onUnmounted, ref, inject } from 'vue';
export default {
name: 'App',
setup() {
const resizeView = ref(false);
const mobileView = ref(false);
const viewData = {
resizeView,
mobileView,
};
const changeResize = () => {
viewData.resizeView.value = !viewData.resizeView.value;
viewData.mobileView.value = !viewData.mobileView.value;
};
const otherViewData = reactive({
mobileView: false,
resizeView: false,
});
const changeReactiveSize = () => {
otherViewData.resizeView = !otherViewData.resizeView;
otherViewData.mobileView = !otherViewData.mobileView;
};
return {
viewData,
otherViewData,
changeResize,
changeReactiveSize,
};
},
components: {
Landscape
}
}
You can also check this code example on stackblitz.